<template>
  <div class="pageStyle">
    <div style="display: flex;">
      <ElScrollbar class="map-left">
        <div class="airline-header mg-b-10">
          <p class="fs-16 fw-bold" style="margin-left:8px">航线概览</p>
          <ElButton class="btn" style="margin-right: 8px;" link type="primary" @click="handleBack()">返回</ElButton>
        </div>
        <div class="airline-distance">
          <div class="flex-1">
            <p class="fs-14" style="font-weight: 800; line-height: 24px">{{ airlineList ? airlineList.length : 0 }}</p>
            <p style="font-size: 12px; line-height: 24px; color: #606266">
              航点数
            </p>
          </div>
          <div class="flex-1">
            <p class="fs-14" style="font-weight: 800; line-height: 24px">
              {{ form.totalDistance ? form.totalDistance.toFixed(0) : 0 }}m</p>
            <p style="font-size: 12px; line-height: 24px; color: #606266">
              预计飞行里程
            </p>
          </div>
          <div class="flex-1">
            <p class="fs-14" style="font-weight: 800; line-height: 24px">{{ formattedTotalTime }}</p>
            <p style="font-size: 12px; line-height: 24px; color: #606266">
              预计飞行时长
            </p>
          </div>
        </div>
        <div class="airline-stoproute mg-b-10" @click="waypointDoubleClick({ index })"
          v-for="(it, index) in airlineList" :key="index" :class="selectedWayPoint == it ? 'airline-distanceblue' : ''">
          <p class="mg-b-20 fw-5 fs-14">
            <span>{{ it.wayPointName }}</span>
            <span>（飞行高度：{{ it.height }} m）</span>
          </p>
          <div class="mg-b-10" style="display: flex;">
            <span class="fs-14" style="width: 75px; color: #606266">航点动作</span>
            <section style="width: calc(100% - 75px);" v-if="it.actions.length > 0">
              <div class="bgimg" style="width: calc(100% / 6.8);" v-for="(item, index) in it.actions" :key="index"
                :title="item.name">
                <ElTooltip effect="light" :content="item.name" placement="top">
                  <img :src="getwayList(item.actionType)?.url || '/static/action1.png'" alt="" />
                </ElTooltip>
              </div>
            </section>
            <span v-else class="fs-14" style="color: #606266">暂无数据</span>
          </div>
          <div class="flex-row-center">
            <span class="fs-14" style="width: 75px; color: #606266">航段</span>
            <section style="width: calc(100% - 75px);" v-if="it.segmentActions.length > 0">
              <div class="bgimg" style="width: calc(100% / 6.8);" v-for="(item, index) in it.segmentActions"
                :key="index" :title="item.name">
                <ElTooltip effect="light" :content="item.name" placement="top">
                  <img :src="getwayList(item.actionType)?.url || '/static/action1.png'" alt="" />
                </ElTooltip>
              </div>
            </section>
            <!-- <section style="width: calc(100% - 75px);" v-if="it.algorithmIds && it.algorithmIds.length > 0">
              <div class="bgimg" style="width: calc(100% / 5.5);" v-for="(item, index) in it.algorithmIds" :key="index"
                :title="getalgorithmList(item)?.label || ''">
                <ElTooltip effect="light" :content="getalgorithmList(item)?.label || ''" placement="top">
                  <img :src="getalgorithmList(item)?.url || '/static/action1.png'" alt="" />
                </ElTooltip>
              </div>
            </section> -->
            <span v-else class="fs-14" style="color: #606266">暂无数据</span>
          </div>
        </div>
        <div style="width: 100%;height: 30px;"></div>
        <div class="pd-10" style="width: 100%;">
          <p class="backbtn" link type="primary" v-if="route.query.id" @click="savetwo('saveAllEdit')">保存并退出</p>
          <p class="backbtn" link type="primary" v-else @click="savetwo('saveAll')">保存并退出</p>
        </div>
      </ElScrollbar>
      <mapPosition ref="mapRef" style="width: 100%" :form="form" :airportList="airportList"
        :flightaltitude="Number(form.globalHeight)" :safetakeoffaltitude="Number(form.takeOffSecurityHeight)"
        :selectedWayPoint="selectedWayPoint" @drawingnext="getdrawingNext" @allData="getallData"
        @startdata="getstartdata" @totalDistance="gettotalDistance" @distanceArray="getdistanceArray"
        @waypointDoubleClick="waypointDoubleClick" :drawDefaultRoute="drawDefaultRoute" />
      <ElScrollbar class="map-right">
        <div class="airline-img mg-b-10">
          <div class="airline-setting flex-row-center" style="margin-bottom: 8px;">
            <p class="fs-14 fw-5">航线名称</p>
            <p class="text" style="font-size: 12px; margin-right: 8px;cursor: pointer;color: #409EFF;"
              v-if="!showEditAirlineName" @click="editAirlineName">
              编辑
            </p>
            <section v-if="showEditAirlineName">
              <span class="text" style="font-size: 12px; margin-right: 8px;cursor: pointer;color: #006be6;"
                @click="cancelAirlineNameEdit">取消</span>
              <span class="text" style="font-size: 12px; margin-right: 8px;cursor: pointer;color: #006be6;"
                @click="saveAirlineName" :class="{ 'disabled-button': !isAirlineNameValid }"
                :disabled="!isAirlineNameValid">确定</span>
            </section>
          </div>
          <div v-if="!showEditAirlineName">
            <ElTooltip effect="light" :content="ruleForm.airlineNameData" placement="top">
              <p class="fs-16 fw-bold"
                style="text-align: left; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; word-wrap: break-word; word-break: break-all; line-height: 1.5em; max-height: 3em;">
                {{ ruleForm.airlineNameData }}</p>
            </ElTooltip>
          </div>
          <div v-if="showEditAirlineName" style="position: relative;">
            <ElForm ref="ruleFormRef" :model="ruleForm" :rules="rules">
              <ElFormItem label="" prop="airlineNameData">
                <!-- v-model="airlineNameData"  -->
                <ElInput v-model="ruleForm.airlineNameData" style="width: 100%;" maxlength="20" show-word-limit
                  type="textarea" autosize placeholder="请输入航线名称" @keydown.enter.prevent="handleEnterKey"
                  @keydown.space.prevent @input="debouncedHandleAirlineNameInput" @keydown="handleAirlineNameKeydown">
                </ElInput>
              </ElFormItem>
            </ElForm>
          </div>
        </div>
        <div class="airline-setup">
          <div class="tab-item fw-5" style="border-right: 1px solid #DCDFE6;cursor: pointer;"
            @click="getActiveName('1')" :class="activeName == '1' ? 'tab-itemBg' : ''">
            航线设置
          </div>
          <div style="cursor: pointer;" class="fw-5" @click="getActiveName('2')"
            :class="activeName == '2' ? 'tab-itemBg' : ''">
            航点设置
          </div>
        </div>
        <div v-if="activeName == '1'">
          <div class="flex-row-center airline-fly">
            <p class="fs-14 fw-5">参考起飞点</p>
            <p class="flex-row-center text fs-14" style="cursor: pointer;">
              <img src="/static/flay.png" alt="" />
              <!-- <span v-show="flayoneShow" @click="oneSetTakeoffMode(false)">参考起飞点未设置</span> -->
              <span v-if="!is_has_takeOffRefPoint" @click="oneSetTakeoffMode()">设置参考起飞点</span>
              <template v-if="is_has_takeOffRefPoint">
                <span v-show="!isResettingTakeoff" @click="enterResetTakeoffMode">重设起飞点</span>
                <span v-show="isResettingTakeoff" @click="cancelResetTakeoffMode">取消设置</span>
              </template>
            </p>
          </div>

          <div class="airline-img mg-b-10">
            <p class="fs-14 fw-5">照片存储类型</p>
            <!-- <ElCheckbox label="广角照片" v-model="form.wideType"></ElCheckbox>
            <ElCheckbox label="变焦照片" v-model="form.zoomType"></ElCheckbox> -->
            <ElCheckbox :true-label="0" :false-label="1" v-model="form.visableType" @change="autoSave">可见光</ElCheckbox>
            <ElCheckbox :true-label="0" :false-label="1" v-model="form.irType" @change="autoSave">红外照片</ElCheckbox>
          </div>
          <div class="airline-img mg-b-10">
            <div class="select-container">
              <span class="select-label">无人机品牌</span>
              <ElSelect v-model="form.brandId" placeholder="请选择无人机品牌" @change="changeBrand" style="width: 100%;"
                class="brand-select">
                <ElOption v-for="item in brandOptions" :key="item.id" :label="item.brandName" :value="item.id" />
              </ElSelect>
            </div>
            <div class="select-container">
              <span class="select-label">系列</span>
              <ElSelect v-model="form.seriesId" placeholder="请选择无人机系列" @change="selectSeries" style="width: 100%;">
                <ElOption v-for="item in seriesList" :key="item.id" :label="item.seriesName" :value="item.id" />
              </ElSelect>
            </div>
            <div class="select-container">
              <span class="select-label">型号</span>
              <ElSelect v-model="form.modelId" placeholder="请选择无人机型号" @change="selectModel" style="width: 100%;">
                <ElOption v-for="item in currentModels" :key="item.id" :label="item.modelName" :value="item.id" />
              </ElSelect>
            </div>
          </div>
          <div class="airline-img mg-b-10">
            <p class="fs-14 fw-5">航线高度模式</p>
            <div class="btn">
              <p style="cursor: pointer;" :class="form.airlineHeightType == 0 ? 'activeBtn' : ''"
                @click="getheightmode(0)">
                <span>相对起飞点高度</span>
              </p>
              <p style="cursor: pointer;" :class="form.airlineHeightType == 1 ? 'activeBtn' : ''"
                @click="getheightmode(1)">
                <span>相对地面高度</span>
              </p>
              <p style="cursor: pointer;" class="marginLeft" :class="form.airlineHeightType == 2 ? 'activeBtn' : ''"
                @click="getheightmode(2)">
                <span>绝对高度</span>
              </p>
            </div>
          </div>
          <div class="pd-10 mg-b-10"
            style="margin: 8px;background: #fff;border: 1px solid #DCDFE6; border-radius: 4px;">
            <div class="airline-setting flex-row-center">
              <p class="fs-14 fw-5">飞行高度</p>
              <p class="text">
                <!-- <ElInputNumber v-model="form.globalHeight" :precision="1" :step="1" :min="min" :max="max"
                  @blur="handleBlur($event, 'globalHeight')" @change="handleGlobalHeightChange" style="width: 75px"
                  :controls="false"></ElInputNumber> -->
                <ElInput v-model="form.globalHeight" style="width: 75px"
                  @input="(val) => fnumberinput('globalHeight', val)"
                  @change="(val) => fnumberchange('globalHeight', val)" />
                <span class="m-l-5" style="font-size: 12px">m</span>
              </p>
            </div>
            <div class="airline-slider">
              <img style="margin: 0;cursor: pointer;" src="/static/delete.png"
                @click="formValueClick('globalHeight', '-')"
                :style="{ cursor: form.globalHeight <= min ? 'not-allowed' : 'pointer' }" alt="" />
              <!-- <ElSlider v-model="sliderGlobalHeight" :min="min" :max="max" :step="1" :show-tooltip="true"
                @change="handleGlobalHeightChange" :format-tooltip="(val) => `${parseFloat(val).toFixed(1)}m`">
              </ElSlider> -->
              <ElSlider v-model="form.globalHeight" :min="min" :max="max" :step="1" :show-tooltip="true"
                @change="(val) => fnumberchange('globalHeight', val)"
                @input="(val) => fnumberinput('globalHeight', val)">
              </ElSlider>
              <img style="margin: 0;cursor: pointer;" @click="formValueClick('globalHeight', '+')"
                :style="{ cursor: form.globalHeight >= max ? 'not-allowed' : 'pointer' }" src="/static/add.png"
                alt="" />
            </div>
            <div class="airline-setting flex-row-center">
              <p class="fs-14 fw-5">飞行速度</p>
              <p class="text">
                <!-- <ElInputNumber v-model="form.autoFlightSpeed" :precision="1" :step="1" :min="minSpeed"
                  :max="maxSpeed" @blur="handleBlur($event, 'autoFlightSpeed')" style="width: 75px"
                  :controls="false"></ElInputNumber> -->
                <ElInput v-model="form.autoFlightSpeed" style="width: 75px"
                  @input="(val) => fnumberinput('autoFlightSpeed', val)"
                  @change="(val) => fnumberchange('autoFlightSpeed', val)" />
                <span class="m-l-5" style="font-size: 12px">m/s</span>
              </p>
            </div>
            <div class="airline-slider">
              <img style="margin: 0;cursor: pointer;" src="/static/delete.png"
                @click="formValueClick('autoFlightSpeed', '-')"
                :style="{ cursor: form.autoFlightSpeed <= minSpeed ? 'not-allowed' : 'pointer' }" alt="" />
              <!-- <ElSlider v-model="sliderAutoFlightSpeed" :min="minSpeed" :max="maxSpeed" :step="1"
                :show-tooltip="true" :format-tooltip="(val) => `${parseFloat(val).toFixed(1)}m/s`"></ElSlider> -->
              <ElSlider v-model="form.autoFlightSpeed" :min="minSpeed" :max="maxSpeed" :step="1" :show-tooltip="true"
                @change="(val) => fnumberchange('autoFlightSpeed', val)"
                @input="(val) => fnumberinput('autoFlightSpeed', val)">
              </ElSlider>
              <img style="margin: 0;cursor: pointer;" src="/static/add.png"
                @click="formValueClick('autoFlightSpeed', '+')"
                :style="{ cursor: form.autoFlightSpeed >= maxSpeed ? 'not-allowed' : 'pointer' }" alt="" />
            </div>
            <div class="airline-setting flex-row-center">
              <p class="fs-14 fw-5">起飞速度</p>
              <p class="text">
                <!-- <ElInput v-model="form.globalTransitionalSpeed"
                  v-decimal-input="{ type: 'number', decimals: 1, min: minSpeed, max: maxSpeed }"
                  @blur="handleBlur($event, 'globalTransitionalSpeed')" style="width: 75px"></ElInput> -->
                <ElInput v-model="form.globalTransitionalSpeed" style="width: 75px"
                  @input="(val) => fnumberinput('globalTransitionalSpeed', val)"
                  @change="(val) => fnumberchange('globalTransitionalSpeed', val)" />
                <span class="m-l-5" style="font-size: 12px">m/s</span>
              </p>
            </div>
            <div class="airline-slider">
              <img style="margin: 0;cursor: pointer;" src="/static/delete.png"
                @click="formValueClick('globalTransitionalSpeed', '-')"
                :style="{ cursor: form.globalTransitionalSpeed <= minSpeed ? 'not-allowed' : 'pointer' }" alt="" />
              <!-- <ElSlider v-model="sliderGlobalTransitionalSpeed" :min="minSpeed" :max="maxSpeed"></ElSlider> -->
              <ElSlider v-model="form.globalTransitionalSpeed" :min="minSpeed" :max="maxSpeed" :step="1"
                :show-tooltip="true" @change="(val) => fnumberchange('globalTransitionalSpeed', val)"
                @input="(val) => fnumberinput('globalTransitionalSpeed', val)">
              </ElSlider>
              <img style="margin: 0;cursor: pointer;" src="/static/add.png"
                @click="formValueClick('globalTransitionalSpeed', '+')"
                :style="{ cursor: form.globalTransitionalSpeed >= maxSpeed ? 'not-allowed' : 'pointer' }" alt="" />
            </div>
          </div>
          <div class="airline-img mg-b-10">
            <p class="fs-14 fw-5">无人机偏航角</p>
            <ElSelect class="select" v-model="form.attitudeHead" placeholder="请选择" @change="autoSave">
              <ElOption v-for="item in yawList" :key="item.value" :label="item.label" :value="item.value" />
            </ElSelect>
          </div>
          <div class="airline-img mg-b-10">
            <p class="fs-14 fw-5">航点类型</p>
            <ElSelect class="select" v-model="form.wayPointType" placeholder="请选择" @change="autoSave">
              <ElOption v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
            </ElSelect>
          </div>
          <!-- <div class="airline-img mg-b-10" >
            <p class="fs-14">无人机失控动作</p>
            <ElSelect
              class="select"
              v-model="form.outOfControlAction"
              placeholder="请选择"
              @change="autoSave"
            >
              <ElOption
                v-for="item in destinationtypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </ElSelect>
          </div> -->
          <div class="airline-img mg-b-20">
            <p class="fs-14">无人机完成动作</p>
            <ElSelect class="select" v-model="form.finishAction" placeholder="请选择">
              <ElOption v-for="item in destinationtypeList" :key="item.value" :label="item.label" :value="item.value" />
            </ElSelect>
          </div>
          <div class="pd-10 mg-b-10"
            style="margin: 8px;background: #fff;border: 1px solid #DCDFE6; border-radius: 4px;">
            <div class="airline-setting flex-row-center">
              <p class="fs-14 fw-5">安全起飞高度</p>
              <p class="text">
                <!-- <ElInputNumber v-model="form.takeOffSecurityHeight" :precision="1" :step="1" :min="1" :max="500"
                  @blur="handleBlur($event, 'takeOffSecurityHeight')" style="width: 75px" :controls="false">
                </ElInputNumber> -->
                <ElInput v-model="form.takeOffSecurityHeight" style="width: 75px" :min="1" :max="500"
                  @input="(val) => fnumberinput('takeOffSecurityHeight', val)"
                  @change="(val) => fnumberchange('takeOffSecurityHeight', val)" />
                <span class="m-l-5">m</span>
              </p>
            </div>
            <div class="airline-slider">
              <img style="margin: 0;cursor: pointer;" src="/static/delete.png"
                @click="formValueClick('takeOffSecurityHeight', '-')"
                :style="{ cursor: form.takeOffSecurityHeight <= 1 ? 'not-allowed' : 'pointer' }" alt="" />
              <!-- <ElSlider v-model="sliderTakeOffSecurityHeight" :min="1" :max="500" :step="1" :show-tooltip="true"
                :format-tooltip="(val) => `${parseFloat(val).toFixed(1)}m`"></ElSlider> -->
              <ElSlider v-model="form.takeOffSecurityHeight" :min="1" :max="500" :step="1" :show-tooltip="true"
                @change="(val) => fnumberchange('takeOffSecurityHeight', val)"
                @input="(val) => fnumberinput('takeOffSecurityHeight', val)"
                :format-tooltip="(val) => `${parseFloat(val).toFixed(1)}m`">
              </ElSlider>
              <img style="margin: 0;cursor: pointer;" src="/static/add.png"
                @click="formValueClick('takeOffSecurityHeight', '+')"
                :style="{ cursor: form.takeOffSecurityHeight >= 500 ? 'not-allowed' : 'pointer' }" alt="" />
            </div>
            <div class="airline-setting flex-row-center">
              <p class="fs-14 fw-5">返航高度</p>
              <p class="text">
                <!-- <ElInputNumber v-model="form.globalRTHHeight" :precision="1" :step="1" :min="1" :max="500"
                  @blur="handleBlur($event, 'globalRTHHeight')" style="width: 75px" :controls="false"></ElInputNumber> -->
                <ElInput v-model="form.globalRTHHeight" style="width: 75px"
                  @input="(val) => fnumberinput('globalRTHHeight', val)"
                  @change="(val) => fnumberchange('globalRTHHeight', val)" />
                <span class="m-l-5">m</span>
              </p>
            </div>
            <div class="airline-slider">
              <img style="margin: 0;cursor: pointer;" src="/static/delete.png"
                @click="formValueClick('globalRTHHeight', '-')"
                :style="{ cursor: form.globalRTHHeight <= 1 ? 'not-allowed' : 'pointer' }" alt="" />
              <!-- <ElSlider v-model="sliderGlobalRTHHeight" :min="1" :max="500" :step="1" :show-tooltip="true"
                :format-tooltip="(val) => `${parseFloat(val).toFixed(1)}m`"></ElSlider> -->
              <ElSlider v-model="form.globalRTHHeight" :min="1" :max="500" :step="1" :show-tooltip="true"
                @change="(val) => fnumberchange('globalRTHHeight', val)"
                @input="(val) => fnumberinput('globalRTHHeight', val)"
                :format-tooltip="(val) => `${parseFloat(val).toFixed(1)}m`">
              </ElSlider>
              <img style="margin: 0;cursor: pointer;" src="/static/add.png"
                @click="formValueClick('globalRTHHeight', '+')"
                :style="{ cursor: form.globalRTHHeight >= 500 ? 'not-allowed' : 'pointer' }" alt="" />
            </div>
          </div>
          <!-- <ElButton class="save" type="primary" @click="saveline(ruleFormRef)">保存设置</ElButton> -->
          <ElButton class="save" type="primary" @click="saveList()">保存设置</ElButton>
        </div>
        <div v-else>
          <div style="margin: 8px">
            <ElSelect class="select" v-model="form_point.wayPointName" placeholder="请选择" @change="getstopenroute"
              @visible-change="showDataloading = false">
              <!-- <ElOption
                v-for="(item,index) in allData[0].points"
                :key="index"
                :label="'航点'+(index+1)"
                :value="index"
              /> -->
              <ElOption v-for="(item, index) in airlineList" :key="index" :label="item.wayPointName" :value="index" />
            </ElSelect>
          </div>
          <section v-loading="showDataloading" element-loading-text="加载中...">
            <div style="background: #fff; border-radius: 4px" class="airline-img pd-10 mg-b-10">
              <div style="padding: 0">
                <p class="fs-14 fw-5">坐标设置</p>
                <ElRadioGroup class="checkbox" v-model="form_point.positionType" @change="updatemap()">
                  <ElRadio label="WGS84" :value="0" />
                  <ElRadio label="百度" :value="1" />
                  <ElRadio label="高德" :value="2" />
                  <ElRadio label="大地2000" :value="3" />
                </ElRadioGroup>
              </div>
              <div class="airline-setting flex-row-center" style="margin-top: 5px;">
                <p class="fs-14" style="width: 15%">经度</p>
                <ElInput v-model="form_point.longitude" style="width: 85%" @change="updateWaypointCoordinates"
                  @input="validateCoordinate" class="address"></ElInput>
                <span class="du">°</span>
              </div>
              <div class="airline-setting flex-row-center" style="margin-top: 10px">
                <p class="fs-14" style="width: 15%">纬度</p>
                <ElInput v-model="form_point.latitude" style="width: 85%" @change="updateWaypointCoordinates"
                  @input="validateCoordinate" class="address"></ElInput>
                <span class="du">°</span>
              </div>
            </div>
            <div style="background: #fff; border-radius: 4px" class="airline-img pd-10 mg-b-10">
              <div class="airline-setting flex-row-center">
                <p class="fs-14 fw-5 waypoint-label">飞行高度</p>
                <ElCheckbox label="跟随航线" @change="linealtitudeClick" v-model="form_point.heightFollow" :true-value="1"
                  :false-value="0" class="follow-checkbox" />
                <p class="text">
                  <ElInputNumber v-model.number.lazy="form_point.height" @change="changeFlightaltitude"
                    @blur="handleFlightaltitudeBlur" style="width: 75px" :controls="false" :precision="1" :step="1"
                    :min="min" :max="max"></ElInputNumber>
                  <span class="m-l-55" style="font-size: 12px">m</span>
                </p>
              </div>
              <div class="airline-slider">
                <img style="margin: 0" src="/static/delete.png" @click="yawaltitudeClick('-')"
                  :disabled="form_point.height <= min" alt="" />
                <ElSlider v-model="sliderFormyawHeight" @input="changeFlightaltitude" @change="changeFlightaltitude"
                  :min="min" :max="max" :step="1" :show-tooltip="true"
                  :format-tooltip="(val) => `${parseFloat(val).toFixed(1)}m`">
                </ElSlider>
                <img style="margin: 0" src="/static/add.png" @click="yawaltitudeClick('+')"
                  :disabled="form_point.height >= max" alt="" />
              </div>
              <div class="airline-setting flex-row-center">
                <p class="fs-14 fw-5 waypoint-label">飞行速度</p>
                <ElCheckbox label="跟随航线" @change="linespeedClick" :true-value="1" :false-value="0"
                  v-model="form_point.waypointSpeedFollow" class="follow-checkbox" />
                <p class="text">
                  <ElInputNumber v-model.number="form_point.flightspeed" @change="changeFlightSpeed" style="width: 75px"
                    :controls="false" :precision="1" :step="1" :min="0" :max="maxSpeed"></ElInputNumber>
                  <span class="m-l-55" style="font-size: 12px">m/s</span>
                </p>
              </div>
              <div class="airline-slider" style="margin-bottom: 0">
                <img style="margin: 0" src="/static/delete.png" @click="yawspeedClick('-')"
                  :disabled="form_point.flightspeed <= 0" alt="" />
                <ElSlider :model-value="sliderFormyawFlightspeed" @update:model-value="val => {
                  const numVal = Number(val);
                  if (!isNaN(numVal)) {
                    form_point.flightspeed = numVal;
                    changeFlightSpeed(numVal);
                  }
                }" :min="minSpeed" :max="maxSpeed" :step="1" :show-tooltip="true"
                  :format-tooltip="(val) => `${parseFloat(val).toFixed(1)}m/s`" />
                <img style="margin: 0" src="/static/add.png" @click="yawspeedClick('+')"
                  :disabled="form_point.flightspeed >= maxSpeed" alt="" />
              </div>
            </div>
            <div class="airline-img mg-b-10">
              <p class="fs-14 fw-5">直播镜头模式</p>
              <ElRadioGroup class="checkbox" v-model="form_point.imageFormat">
                <ElRadio label="广角" :value="0" />
                <ElRadio label="变焦" :value="1" />
                <ElRadio label="红外" :value="2" />
              </ElRadioGroup>
            </div>
            <div class="airline-img mg-b-10">
              <p class="fs-14 fw-5">无人机偏航角</p>
              <ElSelect class="select" v-model="form_point.attitudeHead" placeholder="请选择" @change="updateyaw()">
                <ElOption v-for="item in yawList" :key="item.value" :label="item.label" :value="item.value" />
              </ElSelect>
            </div>
            <div class="pd-10 mg-b-10 airline-img" style="background: #fff; border-radius: 4px">
              <div class="flex-row-center" style="align-items: center;
    justify-content: space-between;padding: 0; margin: 0;">
                <p class="fs-14 fw-5">航点动作</p>
                <ElButton type="primary" link @click="addClick()" style="font-size: 12px;">添加动作
                </ElButton>
              </div>
              <div ref="actionsContainer" class="actions-container"
                style="display: flex; flex-direction: column; gap: 10px;">
                <div v-for="(item, index) in form_point.actions" :key="item.id || `action-${item.actionType}-${index}`"
                  class="airline-wavy sortable-item"
                  style="margin-bottom: 0; background: #f9f9f9; border-radius: 4px; padding: 10px;" :data-index="index">
                  <div class="flex-row-center fs-14 justify-between">
                    <div class="bgimg flex-row-center sortable-handle"
                      style="display: flex; border-radius: 4px; cursor: move;" title="拖拽排序">
                      <img src="/static/action12.png" alt="" class="dragImg" />
                      <span class="m-l-55">{{ item.name }}</span>
                    </div>
                    <div class="flex-row-center">
                      <p class="text" style="margin-right: 4px;" v-if="
                        item.actionType == 1 ||
                        item.actionType == 2 ||
                        item.actionType == 3 ||
                        item.actionType == 7 ||
                        item.actionType == 9 ||
                        item.actionType == 10">
                        <!-- <ElInputNumber v-model.number="item.actionValue" class="numberWidth" style="width: 75px"
                          :controls="false" :precision="([2, 3, 7, 9].includes(item.actionType)) ? 1 : 0" :step="1"
                          :min="item.actionMin" :max="item.actionMax" @blur="(e) => handleActionValueBlur(item, e)"
                          @change="(val) => updateActionValue(item, val)"></ElInputNumber> -->
                        <ElInput v-model="item.actionValue" class="numberWidth" style="width: 75px"
                          @input="(val) => numberBlur(item, val)" @change="(val) => numberchange(item, val)" />
                        <span class="m-l-55" v-if="item.actionType == 1 || item.actionType == 10">S</span>
                        <span class="m-l-55" v-if="item.actionType == 2 || item.actionType == 3">°</span>
                        <span class="m-l-55" v-if="item.actionType == 7">X</span>
                        <span class="m-l-55" v-if="item.actionType == 9">m</span>
                      </p>
                      <Close width="16px" @click="deleteClick(item)" class="delete-icon" />
                    </div>
                  </div>
                  <div class="airline-slider" style="margin-bottom: 0; margin-top: 5px;" v-if="
                    item.actionType == 1 ||
                    item.actionType == 2 ||
                    item.actionType == 3 ||
                    item.actionType == 7 ||
                    item.actionType == 9 ||
                    item.actionType == 10">
                    <img style="margin: 0" src="/static/delete.png" @click="actionValueClick(item, '-')" alt="" />
                    <!-- <ElSlider :model-value="Number(item.actionValue)"
                      @update:model-value="val => updateActionValue(item, val)" :min="Number(item.actionMin)"
                      :max="Number(item.actionMax)" :step="1" :show-tooltip="true"
                      :format-tooltip="(val) => formatActionValueTooltip(item, val)"></ElSlider> -->
                    <ElSlider v-model="item.actionValue" :min="Number(item.actionMin)" :max="Number(item.actionMax)"
                      :step="(item.actionType == 1 || item.actionType == 10) ? 1 : 0.1" :show-tooltip="true"
                      @input="(val) => numberBlur(item, val)" @change="(val) => numberchange(item, val)"></ElSlider>
                    <!-- @update:model-value="val => updateActionValue(item, val)"  :format-tooltip="(val) => formatActionValueTooltip(item, val)"-->
                    <img style="margin: 0" @click="actionValueClick(item, '+')" src="/static/add.png" alt="" />
                  </div>
                </div>
              </div>
            </div>
            <!-- <div class="airline-img mg-b-10">
              <p class="fs-14 fw-5">算法配置</p>
              <ElButton class="airBtn" @click="algorithmClick">配置算法</ElButton>
            </div> -->
            <!-- <div class="airline-img mg-b-10">
              <p class="fs-14 fw-5">喊话配置</p>
              <ElButton class="airBtn" @click="shoutClick">配置喊话</ElButton>
            </div> -->
            <ElButton class="save" type="primary" @click="saveList()">保存设置</ElButton>
          </section>
        </div>

      </ElScrollbar>
      <!-- 配置算法 -->
      <algorithmview v-if="algorithmFlag" @algoView="getalgoView" @getalgoSetting="getalgoSetting" @close="getClose"
        :algorithmConfig="algorithmConfig"></algorithmview>
      <!-- 配置喊话 -->
      <shoutview v-if="shoutFlag" @close="getClose" @getShoutview="getShoutview" :shoutList="shoutList"></shoutview>
    </div>
    <!-- 动作提示窗口 -->
    <div v-if="is_warning" class="warning_box">
      <div class="warning-item" v-for="(item, index) in warning_list" :key="index">
        <div class="warning-item-header">
          <span class="s">问题</span>{{ Number(index) + 1 }}：
          <span v-for="(t, i) in item.points" :key="i">
            {{ t.id }}#
          </span>
          航点的{{ item.question }}
        </div>
        <div class="warning-item-content">
          <span class="s">解决方案</span>：{{ item.solution }}
        </div>
      </div>
    </div>
    <!-- 添加动作 -->
    <waypointaction v-show="waypointactionFlag" ref="waypointactionRef" :airlineList="airlineList"
      :formPoint="form_point" :action="form_point.actions" @close="getClose" @wayView="getwayView">
    </waypointaction>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  onBeforeUnmount,
  defineProps,
  computed,
  watch,
  nextTick,
} from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import Sortable from "sortablejs";
import {
  ElInput,
  ElButton,
  ElScrollbar,
  ElCheckboxGroup,
  ElCheckbox,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadio,
  ElSlider,
  ElTooltip,
  ElMessage,
  ElMessageBox,
  ElLoading,
  ElIcon,
  ElForm,
  ElFormItem,
  ElInputNumber,
} from "element-plus";
import algorithmview from "./algorithmview.vue";
import shoutview from "./shoutview.vue";
import waypointaction from "./waypointaction.vue";
import mapPosition from "./map2.vue";
import { onBeforeRouteLeave } from "vue-router";
import { getAirportListNoPage } from "#/api/sys/equipment";
import { adjustValue } from "./mapdata";
import { router } from "#/router";
import { useRoute } from "vue-router";
import {
  add,
  editAirline,
  getAirlineById,
  coordinateConversion,
  getBrandList,
  getModelList,
  addName,
  editName,
} from "#/api/task/airline";

// import mapPosition from './mapLine.vue';
import {
  yawList,
  typeList,
  stopenrouteList,
  getalgorithmList,
  getwayList,
  destinationtypeList,
} from "./datalist";
const route = useRoute();

const props = defineProps({ showSearch: Boolean });
const airportList = ref([]);
const brandOptions = ref([]); //品牌列表
const seriesList = ref([]); //系列列表
const currentModels = ref([]); //型号列表
// 默认动作配置
const DEFAULT_ACTIONS = [
  {
    name: "无人机偏航角",
    actionType: 2,
    actionValue: 0,
    actionMin: -180,
    actionMax: 180,
    url: "/static/action2.png",
  },
  {
    name: "云台俯仰角",
    actionType: 3,
    actionValue: 0,
    actionMin: -120,
    actionMax: 45,
    url: "/static/action3.png",
  },
  {
    name: "相机变焦",
    actionType: 7,
    actionValue: 1,
    actionMin: 1,
    actionMax: 200,
    url: "/static/action7.png",
  },
];
const showEditAirlineName = ref(false); // 是否显示编辑航线名称
const actionsContainer = ref(null); // 动作容器引用，用于拖拽排序
// const allData = ref([{ points: [] }]);
const startdata = ref({
  point: [],
});
const drawDefaultRoute = ref([]); //默认航线数据
const ruleFormRef = ref();
const ruleForm = reactive({
  airlineNameData: route.query.airlineName,
});
const rules = reactive({
  airlineNameData: [
    { required: true, message: "请输入航线名称", trigger: "blur" },
    { min: 1, max: 20, message: "请输入最多20字", trigger: "blur" },
  ],
});
const totalTime = ref(0); //总飞行时间
const defaultList = ref([]); //默认航线数据
const gaodeList = ref([{ longitude: 0, latitude: 0 }]); //高德坐标默认
// 格式化飞行时间为分钟加秒钟格式
const formattedTotalTime = computed({
  get () {
    if (!totalTime.value || totalTime.value <= 0) {
      return "0min0s";
    }
    // console.log(totalTime.value)
    const totalSeconds = Math.round(totalTime.value);
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;
    return `${minutes}min${seconds}s`;
  },
  set (newValue) {
    if (newValue && newValue.indexOf('min') != -1) {
      let d = newValue.split('min');
      let m = d[0];
      let s = d[1].split('s')[0];
      totalTime.value = parseInt(m) * 60 + Number(s);
    }
    // console.log(totalTime.value)
  }
});
// 需要提交到编辑接口的form 现状的提交只有编辑接口没有添加
const form = reactive({
  id: route.query.id || "",
  airlineName: route.query.airlineName || "", // 航线名称，从路由参数获取
  airlineType: route.query.airlineType || 0,//航线类型 0.点状航线，1.线状航线
  wideType: 1,//0支持广角照片 1.不支持广角照片(暂时写死，通过机型接口获取，接口没传)
  zoomType: 1,//0支持变焦照片 1不支持变焦照片(暂时写死，通过机型接口获取，接口没传)
  airlineHeightType: 0, //航线高度模式  0相对起飞点高度 1相对地面高度 2绝对高度
  globalHeight: 100, //飞行高度
  autoFlightSpeed: 10, //飞行速度
  globalTransitionalSpeed: 10, //起飞速度
  attitudeHead: 0, //偏航角 0沿航线方向 1手动控制 2锁定当前偏航角
  wayPointType: 1, //航点类型
  // 0. 协调转弯，不过点，提前转弯 1. 直线飞行，飞行器点到停 2. 平滑过点，提前转弯 3. 曲线飞行，飞行器到点停 4. 曲线飞行，飞行器过点不停
  outOfControlAction: 0, //无人机失控 0自动返航 1返回航线到起始点悬停 2退出航线模式 3原地降落
  finishAction: 0, //无人机完成动作 0自动返航 1返回航线到起始点悬停 2退出航线模式 3原地降落
  takeOffSecurityHeight: 120, //安全起飞高度
  globalRTHHeight: 120, //全局返航高度
  pointNum: 0, //航点数
  totalDistance: 0, //总距离
  executeTime: formattedTotalTime.value, //执行时间
  wayPoints: [],
  irType: 0, //红外照片// 0代表选中，1代表未选中
  visableType: 0, //可见光照片// 0代表选中，1代表未选中
  takeOffRefPoint: ''//起飞点经纬度用,分割
});
// 航点编辑用的from
const form_point = reactive({
  wayPointName: 0, //航点名称 //索引，不是航点名称
  positionType: 2, //地图
  longitude: null, //经度
  latitude: null, //纬度
  height: 100, //飞行高度
  flightspeed: 10, //飞行速度
  imageFormat: 0, //镜头模式
  attitudeHead: 0, //偏航角
  actions: [], //航点动作
  segmentActions: [], //航段动作
  algorithm: [], //配置算法id集合
  shout: {}, //配置喊话
  algorithmExtends: [], //算法配置
  heightFollow: 1, //跟随航线高度
  waypointSpeedFollow: 1, //跟随航线速度
});

const selectedWayPoint = ref(null); // 选中的航点

// 记录当前航点索引
const waypointIndex = ref(0);
const obj = {
  wayPointName: "",
  longitude: "",
  latitude: "",
  height: 0,
  positionType: 2, //地图
  waypointSpeed: 10,
  imageFormat: 0,
  attitudeHead: 0,
  heightFollow: 1,
  waypointSpeedFollow: 1,
  // actions: [...DEFAULT_ACTIONS],
  actions: [],
  segmentActions: [],
  algorithmIds: [],
  megaphoneOperate: {
    megaphoneOperateLoop: 0,
    megaphoneType: 0,
    megaphoneOperateFile: "",
    text: "",
    playVolume: 0,
  },
};

// 系列选择事件
const selectSeries = (value) => {
  // 检查是否有修改并提示
  if (hasDroneTypeChanged()) {
    ElMessage({
      plain: true,
      message: "更改无人机类型将影响航线作业参数，请谨慎操作!",
      grouping: true,
      type: "warning",
    });
  }

  form.seriesId = value;
  const selectedSeries = seriesList.value.find((series) => series.id == value);
  if (selectedSeries) {
    currentModels.value = selectedSeries.models || [];
    // 默认选中第一个型号
    if (selectedSeries.models && selectedSeries.models.length > 0) {
      form.modelId = selectedSeries.models[0].id;
    } else {
      form.modelId = "";
    }
  } else {
    currentModels.value = [];
    form.modelId = "";
  }
};

// 型号选择事件
const selectModel = (value) => {
  // 检查是否有修改并提示
  if (hasDroneTypeChanged()) {
    ElMessage({
      plain: true,
      message: "更改无人机类型将影响航线作业参数，请谨慎操作!",
      type: "warning",
    });
  }

  form.modelId = value;
};
const airlineList = ref([]);
const shoutList = ref();
const distanceArray = ref([]);
// const airlineNameData = ref(route.query.airlineName);
const airlineform = reactive({
  //表单数据
  airlineHeightType: 0, //航线高度模式  0相对起飞点高度 1相对地面高度 2绝对高度
  // wideType: false, //广角照片
  // zoomType: false, //变焦照片
  irType: 0, //红外照片
  visableType: 0, //可见光照片
  globalHeight: 120, //飞行高度
  autoFlightSpeed: 10, //飞行速度
  globalTransitionalSpeed: 10, //起飞速度
  attitudeHead: 0, //偏航角
  wayPointType: 1, //航点类型
  outOfControlAction: 0, //无人机失控
  finishAction: 0, //无人机完成动作
  takeOffSecurityHeight: 120, //安全起飞高度
  globalRTHHeight: 120, //返航高度
  brandId: route.query.brandId,
  seriesId: route.query.seriesId,
  modelId: route.query.modelId,
});


// 保存初始无人机类型的值，用于比较是否有修改
const initialDroneType = {
  brandId: form.brandId,
  seriesId: form.seriesId,
  modelId: form.modelId,
};

// 检查无人机类型是否有修改
const hasDroneTypeChanged = () => {
  return (
    form.brandId !== initialDroneType.brandId ||
    form.seriesId !== initialDroneType.seriesId ||
    form.modelId !== initialDroneType.modelId
  );
};

// 处理回车键事件，防止换行
const handleEnterKey = (event) => {
  // 阻止默认的换行行为
  event.preventDefault();
  // 可以选择在这里触发保存或其他操作
  // 例如：失去焦点或触发保存
  event.target.blur();
};

// 处理航线名称输入，去除空格和换行符
const handleAirlineNameInput = (value) => {
  // 去除所有空格和换行符
  const cleanedValue = value.replace(/[\s]/g, "");
  if (cleanedValue !== value) {
    ruleForm.airlineNameData = cleanedValue;
  }
};

// 防抖函数
const debounce = (func, wait) => {
  let timeout;
  return function executedFunction (...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

// 防抖版本的输入处理函数
const debouncedHandleAirlineNameInput = debounce((value) => {
  // 去除所有空格和换行符
  const cleanedValue = value.replace(/[\s]/g, "");
  if (cleanedValue !== value) {
    ruleForm.airlineNameData = cleanedValue;
  }
}, 100);

// 处理航线名称按键事件，阻止空格和换行符输入
const handleAirlineNameKeydown = (event) => {
  // 阻止空格键（包括普通空格、制表符等）
  if (event.key === " " || event.key === "Spacebar" || event.keyCode === 32) {
    event.preventDefault();
    return false;
  }
  // 阻止换行键
  if (event.key === "Enter" || event.keyCode === 13) {
    event.preventDefault();
    return false;
  }
};

// 修改 changeBrand 函数
const changeBrand = async () => {
  // 检查是否有修改并提示
  if (hasDroneTypeChanged()) {
    ElMessage({
      plain: true,
      message: "更改无人机类型将影响航线作业参数，请谨慎操作!",
      type: "warning",
    });
  }

  if (!form.brandId) {
    seriesList.value = [];
    currentModels.value = [];
    form.seriesId = "";
    form.modelId = "";
    return;
  }

  await getSeriesByBrandId();
};

// 计算属性确保传递给ElSlider的值是数字类型
// const sliderGlobalHeight = computed({
//   get: () => {
//     const value = Number(form.globalHeight);
//     return isNaN(value) ? min.value : parseFloat(value.toFixed(1));
//   },
//   set: (value) => {
//     const newHeight = parseFloat(Number(value).toFixed(1));
//     form.globalHeight = newHeight;

//     // 只更新勾选了"跟随航线"的航点高度
//     if (airlineList.value && airlineList.value.length > 0) {
//       const updatedList = airlineList.value.map((item, index) => {
//         // 创建新对象确保响应式更新，同时保留所有属性
//         const newItem = {
//           ...item,
//           height: item.heightFollow === 1 ? newHeight : item.height
//         };

//         // 检查未跟随航线的航点，如果高度变得与航线高度一致，则自动勾选跟随
//         // if (item.heightFollow === 0) {
//         //   const heightDiff = Math.abs(item.height - newHeight);
//         //   if (heightDiff < 0.01) {
//         //     newItem.heightFollow = 1;
//         //   }
//         // }

//         return newItem;
//       });

//       // 强制触发响应式更新
//       airlineList.value = updatedList;
//     }

//     // 使用防抖函数来处理频繁的Slider值变化
//     debounceUpdateFollowingWaypointsHeight(value);
//   },
// });


// 修改速度相关的计算属性
const sliderAutoFlightSpeed = computed({
  get: () => {
    const value = Number(form.autoFlightSpeed);
    // 限制在速度范围内
    if (isNaN(value) || value < minSpeed.value) return minSpeed.value;
    if (value > maxSpeed.value) return maxSpeed.value;
    return parseFloat(value.toFixed(1));
  },
  set: (value) => {
    const numValue = parseFloat(Number(value).toFixed(1));
    if (isNaN(numValue)) {
      form.autoFlightSpeed = minSpeed.value;
    } else if (numValue < minSpeed.value) {
      form.autoFlightSpeed = minSpeed.value;
    } else if (numValue > maxSpeed.value) {
      form.autoFlightSpeed = maxSpeed.value;
    } else {
      form.autoFlightSpeed = numValue;
    }

    // 更新所有跟随航线速度的航点
    if (airlineList.value && airlineList.value.length > 0) {
      airlineList.value.forEach((item) => {
        if (item.waypointSpeedFollow == 1) {
          item.waypointSpeed = form.autoFlightSpeed;
        }
        // 检查航点速度是否与航线速度一致，如果不一致则取消跟随（使用精度比较）
        const speedDiff = Math.abs(item.waypointSpeed - form.autoFlightSpeed);
        if (speedDiff >= 0.01) {
          item.waypointSpeedFollow = 0;
        }
      });
      // 强制触发响应式更新
      airlineList.value = [...airlineList.value];
    }
  },
});

const sliderGlobalTransitionalSpeed = computed({
  get: () => {
    const value = Number(form.globalTransitionalSpeed);
    // 限制在速度范围内
    if (isNaN(value) || value < minSpeed.value) return minSpeed.value;
    if (value > maxSpeed.value) return maxSpeed.value;
    return value;
  },
  set: (value) => {
    const numValue = Number(value);
    if (isNaN(numValue)) {
      form.globalTransitionalSpeed = minSpeed.value;
    } else if (numValue < minSpeed.value) {
      form.globalTransitionalSpeed = minSpeed.value;
    } else if (numValue > maxSpeed.value) {
      form.globalTransitionalSpeed = maxSpeed.value;
    } else {
      form.globalTransitionalSpeed = numValue;
    }
  },
});

const sliderTakeOffSecurityHeight = computed({
  get: () => Number(form.takeOffSecurityHeight),
  set: (value) => {
    // 保留一位小数
    form.takeOffSecurityHeight = parseFloat(Number(value).toFixed(1));
  },
});

const sliderGlobalRTHHeight = computed({
  get: () => Number(form.globalRTHHeight),
  set: (value) => {
    // 保留一位小数
    form.globalRTHHeight = parseFloat(Number(value).toFixed(1));
  },
});

const sliderFormyawHeight = computed({
  get: () => {
    // 处理 null, undefined, 或空字符串的情况，设置默认值为0
    if (
      form_point.height === null ||
      form_point.height === undefined ||
      form_point.height === ""
    ) {
      return 0;
    }
    const value = Number(form_point.height);
    return isNaN(value) ? 0 : parseFloat(value.toFixed(1));
  },
  set: (value) => {
    // 通过 setter 传入的 value 通常是由 Slider 组件保证的数字
    form_point.height = parseFloat(Number(value).toFixed(1));

    // 更新跟随状态 - 使用精度比较
    const heightDiff = Math.abs(form_point.height - form.globalHeight);
    // form_point.heightFollow = heightDiff < 0.01 ? 1 : 0;
    // console.log(heightDiff)
    if (heightDiff != 0) {
      form_point.heightFollow = 0
    }

    // 更新航点数据
    if (
      airlineList.value &&
      airlineList.value[waypointIndex.value] !== undefined
    ) {
      airlineList.value[waypointIndex.value].height = form_point.height;
      airlineList.value[waypointIndex.value].heightFollow = form_point.heightFollow;
      // 强制触发响应式更新
      airlineList.value = [...airlineList.value];
    }

    // 触发自动保存
    // autoSave();
  },
});

const sliderFormyawFlightspeed = computed({
  get: () => {
    // 确保返回的是数字类型
    const value = Number(form_point.flightspeed);
    // 航点速度最小值为0，最大值为maxSpeed.value
    if (isNaN(value) || value < 0) return 0;
    if (value > maxSpeed.value) return maxSpeed.value;
    return parseFloat(value.toFixed(1));
  },
  set: (value) => {
    // 确保设置的是数字类型并保留一位小数
    const numValue = parseFloat(Number(value).toFixed(1));
    if (isNaN(numValue) || numValue < 0) {
      form_point.flightspeed = 0;
    } else if (numValue > maxSpeed.value) {
      form_point.flightspeed = maxSpeed.value;
    } else {
      form_point.flightspeed = numValue;
    }

    // 更新跟随状态 - 只有当航点速度与航线速度一致时才勾选跟随（使用精度比较）
    const speedDiff = Math.abs(form_point.flightspeed - form.autoFlightSpeed);
    // form_point.waypointSpeedFollow = speedDiff < 0.01 ? 1 : 0;
    if (speedDiff != 0) {
      form_point.waypointSpeedFollow = 0
    }

    // 更新航点数据
    if (
      airlineList.value &&
      airlineList.value[waypointIndex.value] !== undefined
    ) {
      airlineList.value[waypointIndex.value].waypointSpeed = form_point.flightspeed;
      airlineList.value[waypointIndex.value].waypointSpeedFollow = form_point.waypointSpeedFollow;

      // 强制触发响应式更新
      airlineList.value = [...airlineList.value];
    }

    // 触发自动保存
    // autoSave();
  },
});

// 为actionValue创建计算属性的辅助函数
const createActionValueComputed = (item) => {
  return computed({
    get: () => Number(item.actionValue),
    set: (value) => {
      item.actionValue = value;
    },
  });
};

// 算法
const algorithmList = ref([]);
const algorithmConfig = ref({
  algorithmList: algorithmList.value,
  algorithmExtends: form_point.algorithmExtends,
});
const activeName = ref("1");
// const linealtitudeShow = ref(true); // 跟随航线高度选择框
// const linespeedShow = ref(true); // 跟随航线速度选择框
const linealtitude = ref(0); // 跟随航线高度
const linespeed = ref(0); // 跟随航线速度
const min = ref(1); // 最小值
const max = ref(500); // 最大值
const minSpeed = ref(1); // 最小速度
const maxSpeed = ref(15); // 最大速度
const status = ref("");
const shoutFlag = ref(false);
const algorithmFlag = ref(false);
const waypointactionRef = ref(null);
const waypointactionFlag = ref(false);

const draw_mode = ref(1); //1 起飞点绘制 2 航线绘制 3不绘制
const is_has_takeOffRefPoint = ref(false); // 是否有起飞点(为了方便显示)

// const flayShow = ref(true); // true 重设起飞点  fALSE取消设置
// const flayoneShow = ref(true); // 参考起飞点未设置
const isResettingTakeoff = ref(false); // 是否正在重设起飞点模式
const showDataloading = ref(false);
// 添加用于控制自动保存的标志位
const isInitialLoad = ref(true); // 是否是首次加载
const hasTakeoffPoint = ref(false); // 是否有起飞点数据
const hasWaypointData = ref(false); // 是否有航点数据

// 添加自动保存防抖定时器
let autoSaveDebounceTimer = null;
const AUTO_SAVE_DEBOUNCE_DELAY = 500; // 500ms防抖延迟

// 获取系列列表
const getSeriesByBrandId = async () => {
  if (!form.brandId) return;

  const params = {
    brandId: form.brandId,
  };

  try {
    const { data } = await getModelList(params);
    seriesList.value = data || [];

    // 从路由参数中获取系列ID和型号ID，并转换为字符串类型
    const routeSeriesId = String(
      route.query.seriesId || ""
    );
    const routeModelId = String(route.query.modelId || "");

    // 如果路由中有系列ID，则设置并加载对应的型号
    if (
      routeSeriesId &&
      routeSeriesId !== "undefined" &&
      routeSeriesId !== "null"
    ) {
      // 查找对应的系列
      const selectedSeries = seriesList.value.find(
        (series) => String(series.id) === routeSeriesId
      );

      if (selectedSeries) {
        form.seriesId = selectedSeries.id;
        currentModels.value = selectedSeries.models || [];

        // 如果路由中有型号ID，则设置
        if (
          routeModelId &&
          routeModelId !== "undefined" &&
          routeModelId !== "null"
        ) {
          // 查找对应的型号
          const selectedModel = currentModels.value.find(
            (model) => String(model.id) === routeModelId
          );

          if (selectedModel) {
            form.modelId = selectedModel.id;
          } else if (currentModels.value.length > 0) {
            // 默认选中第一个型号
            form.modelId = currentModels.value[0].id;
          } else {
            form.modelId = "";
          }
        } else if (currentModels.value.length > 0) {
          // 默认选中第一个型号
          form.modelId = currentModels.value[0].id;
        } else {
          form.modelId = "";
        }
      } else if (seriesList.value.length > 0) {
        // 路由中的系列ID无效，默认选中第一个系列
        const firstSeries = seriesList.value[0];
        form.seriesId = firstSeries.id;
        currentModels.value = firstSeries.models || [];

        // 默认选中第一个型号
        if (currentModels.value.length > 0) {
          form.modelId = currentModels.value[0].id;
        } else {
          form.modelId = "";
        }
      } else {
        // 清空系列和型号
        form.seriesId = "";
        currentModels.value = [];
        form.modelId = "";
      }
    } else if (seriesList.value.length > 0) {
      // 默认选中第一个系列
      const firstSeries = seriesList.value[0];
      form.seriesId = firstSeries.id;
      currentModels.value = firstSeries.models || [];

      // 默认选中第一个型号
      if (currentModels.value.length > 0) {
        form.modelId = currentModels.value[0].id;
      } else {
        form.modelId = "";
      }
    } else {
      // 清空系列和型号
      form.seriesId = "";
      currentModels.value = [];
      form.modelId = "";
    }
  } catch (error) {
    ElMessage.error("获取系列列表失败");
    console.error(error);
  }
};

const handleBack = () => {
  let message = "若未保存数据将失效，确定要返回吗?";
  try {
    ElMessageBox.confirm(message, "提示", {
      type: "success",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      beforeClose: async (action, instance, done) => {
        if (action === "confirm") {
          instance.confirmButtonLoading = true;
          try {
            await router.go(-1);
            done();
          } catch (error) {
            instance.confirmButtonLoading = false;
            // 如果是取消导航，不显示错误
            if (error !== "cancel") {
              console.error("导航失败:", error);
            }
          }
        } else {
          done();
        }
      },
    });
  } catch (error) {
    // 忽略取消操作的错误
    if (error !== "cancel") {
      ElMessage.error(`退出失败: ${error.message || "未知错误"}`);
      console.error("退出失败:", error);
    }
  }
};

//坐标转换
const coordinateData = async (option) => {
  const params = {
    longitude: option.longitude,
    latitude: option.latitude,
    method: option.method,
  };
  const { data } = await coordinateConversion(params);
  return data;
};

// 飞行高度
const flightaltitudeClick = (option) => {
  let currentHeight =
    typeof form.globalHeight === "string"
      ? parseFloat(form.globalHeight)
      : Number(form.globalHeight);

  if (isNaN(currentHeight)) currentHeight = min.value;
  const change = option === "-" ? -1 : option === "+" ? 1 : 0;

  // 计算新值并确保在范围内
  let newHeight = currentHeight + change;
  newHeight = Math.max(min.value, Math.min(max.value, newHeight));

  // 保留一位小数
  const formattedNewHeight = parseFloat(newHeight.toFixed(1));
  form.globalHeight = formattedNewHeight;

  // 只更新勾选了"跟随航线"的航点高度
  if (airlineList.value && airlineList.value.length > 0) {
    const updatedList = airlineList.value.map((item, index) => {
      // 创建新对象确保响应式更新，同时保留所有属性
      const newItem = {
        ...item,
        height: item.heightFollow === 1 ? formattedNewHeight : item.height
      };

      // 检查未跟随航线的航点，如果高度变得与航线高度一致，则自动勾选跟随
      // if (item.heightFollow === 0) {
      //   const heightDiff = Math.abs(item.height - formattedNewHeight);
      //   if (heightDiff < 0.01) {
      //     newItem.heightFollow = 1;
      //   }
      // }

      return newItem;
    });

    // 强制触发响应式更新
    airlineList.value = updatedList;
  }

  // 使用防抖函数来处理频繁的值变化
  debounceUpdateFollowingWaypointsHeight(formattedNewHeight);
};

// 处理航线飞行高度变化事件
const handleGlobalHeightChange = (newVal, oldVal) => {
  // 确保新值是有效数字
  const numericNewVal = Number(newVal);
  if (isNaN(numericNewVal)) return;

  // 保留一位小数
  const formattedNewVal = parseFloat(numericNewVal.toFixed(1));
  form.globalHeight = formattedNewVal;

  // 只更新勾选了"跟随航线"的航点高度
  if (airlineList.value && airlineList.value.length > 0) {
    const updatedList = airlineList.value.map((item, index) => {
      // 创建新对象确保响应式更新，同时保留所有属性
      const newItem = {
        ...item,
        height: item.heightFollow === 1 ? formattedNewVal : item.height
      };

      // 检查未跟随航线的航点，如果高度变得与航线高度一致，则自动勾选跟随
      // if (item.heightFollow === 0) {
      //   const heightDiff = Math.abs(item.height - formattedNewVal);
      //   if (heightDiff < 0.01) {
      //     newItem.heightFollow = 1;
      //   }
      // }

      return newItem;
    });

    // 强制触发响应式更新
    airlineList.value = updatedList;
  }

  // 使用防抖函数来处理频繁的值变化
  debounceUpdateFollowingWaypointsHeight(formattedNewVal);
};

// 截取指定小数位数而不四舍五入
const truncateToDecimalPlaces = (num, decimals) => {
  const factor = Math.pow(10, decimals);
  return (Math.trunc(num * factor) / factor).toFixed(decimals);
};

// 飞行速度
const flightspeedClick = (option) => {
  let currentSpeed =
    typeof form.autoFlightSpeed === "string"
      ? parseFloat(form.autoFlightSpeed)
      : Number(form.autoFlightSpeed);

  if (isNaN(currentSpeed)) currentSpeed = minSpeed.value;

  // 使用1作为步进值
  const change = option === "-" ? -1 : option === "+" ? 1 : 0;

  // 计算新值并确保在范围内
  let newSpeed = currentSpeed + change;
  newSpeed = Math.max(minSpeed.value, Math.min(maxSpeed.value, newSpeed));

  // 保留一位小数
  const formattedNewSpeed = parseFloat(newSpeed.toFixed(1));
  form.autoFlightSpeed = formattedNewSpeed;

  // 只更新勾选了"跟随航线"的航点速度
  if (airlineList.value && airlineList.value.length > 0) {
    airlineList.value.forEach((item) => {
      // 只有当航点设置为跟随航线时才更新速度
      if (item.waypointSpeedFollow === 1) {
        item.waypointSpeed = formattedNewSpeed;
      }
      // 检查未跟随航线的航点，如果速度变得与航线速度一致，则自动勾选跟随
      // else if (item.waypointSpeedFollow === 0) {
      //   const speedDiff = Math.abs(item.waypointSpeed - formattedNewSpeed);
      //   if (speedDiff < 0.01) {
      //     item.waypointSpeedFollow = 1;
      //   }
      // }
    });
    // 强制触发响应式更新
    airlineList.value = [...airlineList.value];
  }

  // 添加防抖自动保存
  // debouncedAutoSave();
};
// 起飞速度
const takeoffspeedClick = (option) => {
  if (typeof form.globalTransitionalSpeed == "string") {
    form.globalTransitionalSpeed = parseFloat(form.globalTransitionalSpeed);
  }
  // 确保当前值在有效范围内
  if (
    isNaN(form.globalTransitionalSpeed) ||
    form.globalTransitionalSpeed < minSpeed.value
  ) {
    form.globalTransitionalSpeed = minSpeed.value;
  } else if (form.globalTransitionalSpeed > maxSpeed.value) {
    form.globalTransitionalSpeed = maxSpeed.value;
  }

  const change =
    {
      "-": -1,
      "+": 1,
    }[option] || 0;

  form.globalTransitionalSpeed = adjustValue(
    form.globalTransitionalSpeed,
    change,
    minSpeed.value, // 使用速度最小值
    maxSpeed.value
  );

  // 添加防抖自动保存
  // debouncedAutoSave();
};
//安全起飞高度
const safetakeoffaltitudeClick = (option) => {
  let currentHeight =
    typeof form.takeOffSecurityHeight === "string"
      ? parseFloat(form.takeOffSecurityHeight)
      : Number(form.takeOffSecurityHeight);

  if (isNaN(currentHeight)) currentHeight = 1;

  // 使用1作为步进值
  const change = option === "-" ? -1 : option === "+" ? 1 : 0;

  // 计算新值并确保在范围内
  let newHeight = currentHeight + change;
  newHeight = Math.max(1, Math.min(500, newHeight));

  // 保留一位小数
  form.takeOffSecurityHeight = parseFloat(newHeight.toFixed(1));

  // 添加防抖自动保存
  // debouncedAutoSave();
};
//返航高度
const returnaltitudeClick = (option) => {
  let currentHeight =
    typeof form.globalRTHHeight === "string"
      ? parseFloat(form.globalRTHHeight)
      : Number(form.globalRTHHeight);

  if (isNaN(currentHeight)) currentHeight = 1;

  // 使用1作为步进值
  const change = option === "-" ? -1 : option === "+" ? 1 : 0;

  // 计算新值并确保在范围内
  let newHeight = currentHeight + change;
  newHeight = Math.max(1, Math.min(500, newHeight));

  // 保留一位小数
  form.globalRTHHeight = parseFloat(newHeight.toFixed(1));

  // 添加防抖自动保存
  // debouncedAutoSave();
};
// // 无人机失控
// const destinationtypeClick = (option) => {
//   if (option == '-') {
//     if (form.destinationtype < max.value) {
//       form.destinationtype -= 1;
//     }
//   }
// };

// 飞行高度
const yawaltitudeClick = (option) => {
  let currentHeight =
    typeof form_point.height === "string"
      ? parseFloat(form_point.height)
      : Number(form_point.height);

  if (isNaN(currentHeight)) currentHeight = min.value;

  // 使用1作为步进值
  const change = option === "-" ? -1 : option === "+" ? 1 : 0;

  // 计算新值并确保在范围内
  let newHeight = currentHeight + change;
  newHeight = Math.max(min.value, Math.min(max.value, newHeight));

  // 保留一位小数
  form_point.height = parseFloat(newHeight.toFixed(1));
  sliderFormyawHeight.value = form_point.height;
  changeFlightaltitude(form_point.height);
  // 更新跟随状态（使用精度比较）
  const heightDiff = Math.abs(form_point.height - form.globalHeight);
  // form_point.heightFollow = heightDiff < 0.01 ? 1 : 0;
  // console.log(heightDiff)
  if (heightDiff != 0) {
    form_point.heightFollow = 0
  }
  airlineList.value[waypointIndex.value].height = form_point.height;
  airlineList.value[waypointIndex.value].heightFollow = form_point.heightFollow;

  // 强制触发响应式更新，确保地图组件能监听到变化
  // airlineList.value = [...airlineList.value];

  // 添加自动保存
  // saveline();
  if (mapRef.value) {
    mapRef.value.getPointHeght(form_point);
  }
};
// 飞行速度
const yawspeedClick = (option) => {
  // 确保 form_point.flightspeed 是数字类型
  let currentSpeed = Number(form_point.flightspeed);
  if (isNaN(currentSpeed)) currentSpeed = 0;

  // 使用1作为步进值
  const change = option === "-" ? -1 : option === "+" ? 1 : 0;

  // 计算新值并确保在范围内
  let newSpeed = currentSpeed + change;
  newSpeed = Math.max(0, Math.min(maxSpeed.value, newSpeed));

  // 保留一位小数
  form_point.flightspeed = parseFloat(newSpeed.toFixed(1));

  // 更新跟随状态（使用精度比较）
  const speedDiff = Math.abs(form_point.flightspeed - form.autoFlightSpeed);
  // form_point.waypointSpeedFollow = speedDiff < 0.01 ? 1 : 0;
  if (speedDiff != 0) {
    form_point.waypointSpeedFollow = 0
  }

  airlineList.value[waypointIndex.value].waypointSpeed = Number(
    form_point.flightspeed
  );
  airlineList.value[waypointIndex.value].waypointSpeedFollow =
    form_point.waypointSpeedFollow;

  // 触发changeFlightSpeed来同步其他状态
  changeFlightSpeed(form_point.flightspeed);
};
// 航线的数值和加减变动
const formValueClick = (item, option) => {
  form[item] = Number(form[item]);
  const step = 1;
  let minnum, maxnum;
  if (item == 'globalTransitionalSpeed' || item == 'autoFlightSpeed') {
    minnum = minSpeed.value
    maxnum = maxSpeed.value
  } else {
    minnum = min.value
    maxnum = max.value
  }
  if (option == "-") {
    let newValue = (form[item] * 10 - step * 10) / 10;
    if (newValue < minnum) {
      form[item] = minnum;
    } else {
      form[item] = newValue;
    }
  } else if (option == "+") {
    let newValue = (form[item] * 10 + step * 10) / 10;
    if (newValue > maxnum) {
      form[item] = maxnum;
    } else {
      form[item] = newValue;
    }
  }
  // 计算飞行时长
  getflighttime(airlineList.value);
};
const fnumberinput = (item, val) => {
  if (!val && val !== 0) return;
  let str = val.toString().trim().replace(/\s/g, "");
  if (!str && str !== 0 || str == '') {
    form[item] = '';
    return;
  };
  //检查第一位不能是.
  if (str.startsWith('.') && str.length == 1) {
    str = ''; // 移除.
    form[item] = '';
    return
  }
  let result = str.replace(/[^0-9.-]/g, '');
  // 确保负号只出现在开头
  const negativeCount = result.split('-').length - 1;
  if (negativeCount > 1 || (negativeCount === 1 && !result.startsWith('-'))) {
    result = result.replace(/(?!^)-/g, ''); //移除非开头的负号
  }
  // 校验结尾 . 或 -，并检查倒数第二位
  if (result.endsWith('.') || result.endsWith('-')) {
    const secondLastChar = result.length > 1 ? result[result.length - 2] : '';
    if (secondLastChar === '-' || secondLastChar === '.') {
      result = result.substring(0, result.length - 1);
    }
  }
  // 找到第一个点号的位置
  const firstDotIndex = result.indexOf('.');
  if (firstDotIndex !== -1) {
    // 保留第一个点号及其前后的数字，移除多余的点号
    result = result.substring(0, firstDotIndex + 1) + result.substring(firstDotIndex + 1).replace(/\./g, '');
    // 限制小数点后最多一位
    const parts = result.split('.');
    if (parts[1] && parts[1].length > 1) {
      parts[1] = parts[1].substring(0, 1);
      result = parts.join('.');
    }
  }
  let minnum, maxnum;
  if (item == 'globalTransitionalSpeed' || item == 'autoFlightSpeed') {
    minnum = minSpeed.value
    maxnum = maxSpeed.value
  } else if (item == 'takeOffSecurityHeight' || item == 'globalRTHHeight') {
    minnum = 1
    maxnum = 500
  } else {
    minnum = min.value
    maxnum = max.value
  }
  if (!result.endsWith('.') && !result.endsWith('-')) {
    let nnum = parseFloat(result)
    if (nnum < minnum) {
      nnum = minnum;
    }
    if (nnum > maxnum) {
      nnum = maxnum;
    }
    form[item] = nnum
  } else {
    form[item] = result
  }
}
const fnumberchange = (item, val) => {
  if (!val && val !== 0) {
    if (item == 'globalHeight') {
      form.globalHeight = 100; //飞行高度
    } else if (item == 'autoFlightSpeed') {
      form.autoFlightSpeed = 10; //飞行速度
    } else if (item == 'globalTransitionalSpeed') {
      form.globalTransitionalSpeed = 10; //飞行速度
    } else if (item == 'takeOffSecurityHeight') {
      form.takeOffSecurityHeight = 120; //飞行速度
    } else if (item == 'globalRTHHeight') {
      form.globalRTHHeight = 120; //飞行速度
    }
    // switch (item) {
    //   case 'globalHeight':
    //     form.globalHeight = 100; //飞行高度
    //   case 'autoFlightSpeed':
    //     form[item] = 10; //飞行速度
    //   case 'globalTransitionalSpeed':
    //     form[item] = 10; //起飞速度
    //   case 'takeOffSecurityHeight':
    //     form[item] = 120; //安全起飞高度
    //   case 'globalRTHHeight':
    //     form[item] = 120; //返航高度
    //   default:
    //     form[item] = 0;
    // }
    // console.log(item, form[item])
    return;
  }
  let str = val.toString();
  if (str.startsWith('.') && str.length == 1) {
    str = ''; // 移除.
    form[item] = '';
    return
  }
  let result = str.replace(/[^0-9.-]/g, '');
  // 确保负号只出现在开头
  const negativeCount = result.split('-').length - 1;
  if (negativeCount > 1 || (negativeCount === 1 && !result.startsWith('-'))) {
    result = result.replace(/(?!^)-/g, ''); //移除非开头的负号
  }
  // 校验结尾 . 或 -，并检查倒数第二位
  if (result.endsWith('.') || result.endsWith('-')) {
    const secondLastChar = result.length > 1 ? result[result.length - 2] : '';
    if (secondLastChar === '-' || secondLastChar === '.') {
      result = result.substring(0, result.length - 1);
    }
  }
  // 找到第一个点号的位置
  const firstDotIndex = result.indexOf('.');
  if (firstDotIndex !== -1) {
    // 保留第一个点号及其前后的数字，移除多余的点号
    result = result.substring(0, firstDotIndex + 1) + result.substring(firstDotIndex + 1).replace(/\./g, '');
    // 限制小数点后最多一位
    const parts = result.split('.');
    if (parts[1] && parts[1].length > 1) {
      parts[1] = parts[1].substring(0, 1);
      result = parts.join('.');
    }
  }
  let minnum, maxnum;
  if (item == 'globalTransitionalSpeed' || item == 'autoFlightSpeed') {
    minnum = minSpeed.value
    maxnum = maxSpeed.value
  } else if (item == 'takeOffSecurityHeight' || item == 'globalRTHHeight') {
    minnum = 1
    maxnum = 500
  } else {
    minnum = min.value
    maxnum = max.value
  }
  let nnum = parseFloat(result)
  if (nnum < minnum) {
    nnum = minnum;
  }
  if (nnum > maxnum) {
    nnum = maxnum;
  }
  form[item] = nnum;
  // 计算飞行时长
  getflighttime(airlineList.value);
}
// 动作的加减动作数值
const actionValueClick = (item, option) => {
  item.actionValue = Number(item.actionValue);
  const needDecimal = [2, 3, 7, 9].includes(item.actionType);
  const step = needDecimal ? 0.1 : 1;
  if (option == "-") {
    let newValue = (item.actionValue * 10 - step * 10) / 10;
    if (newValue < item.actionMin) {
      item.actionValue = item.actionMin;
    } else {
      item.actionValue = newValue
    }
  } else if (option == "+") {
    let newValue = (item.actionValue * 10 + step * 10) / 10;
    if (newValue > item.actionMax) {
      item.actionValue = item.actionMax;
    } else {
      item.actionValue = newValue
    }
  }
};
// 动作的input监听 数字赋值
const numberBlur = (item, val) => {
  if (!val && val !== 0) return;
  let str = val.toString();
  if (str.startsWith('.') && str.length == 1) {
    str = ''; // 移除.
    item.actionValue = ''
    return
  }
  let result = str.replace(/[^0-9.-]/g, '');
  // 确保负号只出现在开头
  const negativeCount = result.split('-').length - 1;
  if (negativeCount > 1 || (negativeCount === 1 && !result.startsWith('-'))) {
    result = result.replace(/(?!^)-/g, ''); //移除非开头的负号
  }
  // 校验结尾 . 或 -，并检查倒数第二位
  if (result.endsWith('.') || result.endsWith('-')) {
    const secondLastChar = result.length > 1 ? result[result.length - 2] : '';
    if (secondLastChar === '-' || secondLastChar === '.') {
      result = result.substring(0, result.length - 1);
    }
  }
  // 找到第一个点号的位置
  const firstDotIndex = result.indexOf('.');
  if (firstDotIndex !== -1) {
    // 保留第一个点号及其前后的数字，移除多余的点号
    result = result.substring(0, firstDotIndex + 1) + result.substring(firstDotIndex + 1).replace(/\./g, '');
    // 限制小数点后最多一位
    const parts = result.split('.');
    if (parts[1] && parts[1].length > 1) {
      parts[1] = parts[1].substring(0, 1);
      result = parts.join('.');
    }
  }
  const needDecimal = [2, 3, 7, 9].includes(item.actionType);
  if (needDecimal) {
    if (!result.endsWith('.') && !result.endsWith('-')) {
      let nnum = parseFloat(result)
      if (nnum < item.actionMin) {
        nnum = item.actionMin;
      }
      if (nnum > item.actionMax) {
        nnum = item.actionMax;
      }
      item.actionValue = nnum
    } else {
      item.actionValue = nnum
    }
  } else {
    const numbers = result.replace(/-/g, '').match(/\d+/g);
    let nnum = Number(numbers ? parseInt(numbers.join(''), 10).toString() : '');
    if (isNaN(nnum)) {
      nnum = 0;
    } else {
      if (nnum < item.actionMin) {
        nnum = item.actionMin;
      }
      if (nnum > item.actionMax) {
        nnum = item.actionMax;
      }
    }
    item.actionValue = nnum;
  }
};
// 动作的change监听 数字赋值
const numberchange = (item, val) => {
  if (!val && val !== 0) {
    switch (item.actionType) {
      case 1:
        item.actionValue = 10;
      case 2: // 无人机偏航角
        item.actionValue = 0;
      case 3: // 云台俯仰角
        item.actionValue = 0;
        break;
      case 7: // 相机变焦
        item.actionValue = 2;
        break;
      case 9: // 开始等距间隔拍照
        item.actionValue = 10; // 明确设置为10
        break;
      case 9:
        item.actionValue = 15;
        break;
      default:
        item.actionValue = needDecimal ? 0.0 : 0;
    }
    return;
  }
  let str = val.toString()
  if (str.startsWith('.') && str.length == 1) {
    str = ''; // 移除.
    item.actionValue = ''
    return
  }
  let result = str.replace(/[^0-9.-]/g, '');
  // 确保负号只出现在开头
  const negativeCount = result.split('-').length - 1;
  if (negativeCount > 1 || (negativeCount === 1 && !result.startsWith('-'))) {
    result = result.replace(/(?!^)-/g, ''); //移除非开头的负号
  }
  // 校验结尾 . 或 -，并检查倒数第二位
  if (result.endsWith('.') || result.endsWith('-')) {
    const secondLastChar = result.length > 1 ? result[result.length - 2] : '';
    if (secondLastChar === '-' || secondLastChar === '.') {
      result = result.substring(0, result.length - 1);
    }
  }
  // 找到第一个点号的位置
  const firstDotIndex = result.indexOf('.');
  if (firstDotIndex !== -1) {
    // 保留第一个点号及其前后的数字，移除多余的点号
    result = result.substring(0, firstDotIndex + 1) + result.substring(firstDotIndex + 1).replace(/\./g, '');
    // 限制小数点后最多一位
    const parts = result.split('.');
    if (parts[1] && parts[1].length > 1) {
      parts[1] = parts[1].substring(0, 1);
      result = parts.join('.');
    }
  }
  const needDecimal = [2, 3, 7, 9].includes(item.actionType);
  if (needDecimal) {
    let nnum = parseFloat(result)
    if (nnum < item.actionMin) {
      nnum = item.actionMin;
    }
    if (nnum > item.actionMax) {
      nnum = item.actionMax;
    }
    item.actionValue = nnum
  } else {
    const numbers = result.replace(/-/g, '').match(/\d+/g);
    let nnum = Number(numbers ? parseInt(numbers.join(''), 10).toString() : '');
    if (isNaN(nnum)) {
      nnum = 0;
    } else {
      if (nnum < item.actionMin) {
        nnum = item.actionMin;
      }
      if (nnum > item.actionMax) {
        nnum = item.actionMax;
      }
    }
    item.actionValue = nnum;
  }
}
// 新增更新动作值函数
const updateActionValue = (item, val) => {
  const needDecimal = [2, 3, 7, 9].includes(item.actionType);
  const numVal = Number(val);
  console.log(val)
  // 处理空值或无效值
  if (
    isNaN(numVal) ||
    numVal === null ||
    numVal === undefined ||
    numVal === ""
  ) {
    // 根据 actionType 设置不同的默认值
    switch (item.actionType) {
      case 2: // 无人机偏航角
        item.actionValue = 0;
      case 3: // 云台俯仰角
        item.actionValue = 0;
        break;
      case 7: // 相机变焦
        item.actionValue = 2;
        break;
      case 9: // 开始等距间隔拍照
        item.actionValue = 10; // 明确设置为10
        break;
      default:
        item.actionValue = needDecimal ? 0.0 : 0;
    }
  } else {
    // item.actionType == 1 || item.actionType == 10
    // 确保值在有效范围内
    console.log(item)
    let clampedValue = Math.max(
      item.actionMin,
      Math.min(item.actionMax, numVal)
    );
    console.log(clampedValue, needDecimal)
    item.actionValue = needDecimal
      ? parseFloat(clampedValue.toFixed(1))
      : clampedValue.toFixed(0);
  }
  // autoSave();
  // 触发防抖自动保存
  // debouncedAutoSave();
};

const handleActionValueBlur = (item, event) => {
  const value = Number(item.actionValue);

  // 检查是否为空值或无效值
  if (
    isNaN(value) ||
    item.actionValue === null ||
    item.actionValue === undefined ||
    item.actionValue === ""
  ) {
    // 根据 actionType 设置不同的默认值
    switch (item.actionType) {
      case 2: // 无人机偏航角
      case 3: // 云台俯仰角
        item.actionValue = 0;
        break;
      case 7: // 相机变焦
        item.actionValue = 2;
        break;
      case 9: // 开始等距间隔拍照
        item.actionValue = 10; // 确保这里设置为10
        break;
      default:
        item.actionValue = 0;
    }

    // 触发更新以确保视图同步
    updateActionValue(item, item.actionValue);
  }
};

// 新增格式化滑块提示函数
const formatActionValueTooltip = (item, val) => {
  const needDecimal = [2, 3, 7, 9].includes(item.actionType);

  // 处理空值情况
  if (val === null || val === undefined || val === "") {
    switch (item.actionType) {
      case 2: // 无人机偏航角
        return "0";
      case 3: // 云台俯仰角
        return "0";
      case 7: // 相机变焦
        return "2";
      case 9: // 开始等距间隔拍照
        return "10";
      default:
        return needDecimal ? "0.0" : "0";
    }
  }

  return needDecimal ? `${parseFloat(val).toFixed(1)}` : val.toFixed(0);
};

// 跟随高度
const linealtitudeClick = (val) => {
  if (val == 1) {
    // 设置为跟随航线
    form_point.height = form.globalHeight;
    // 更新航点数据
    airlineList.value[waypointIndex.value].height = form.globalHeight;
    airlineList.value[waypointIndex.value].heightFollow = 1;
  } else {
    // 取消跟随航线，保持当前高度不变
    // 检查defaultList是否存在且有对应索引的数据
    // if (route.query.id &&
    //   defaultList.value &&
    //   defaultList.value[waypointIndex.value] !== undefined) {
    //   form_point.height = defaultList.value[waypointIndex.value].height;
    //   // 更新航点数据
    //   airlineList.value[waypointIndex.value].height = defaultList.value[waypointIndex.value].height;
    // } else {
    //   // 对于新创建的航点，使用当前高度值
    //   form_point.height = airlineList.value[waypointIndex.value].height;
    // }
    // 设置为不跟随
    airlineList.value[waypointIndex.value].heightFollow = 0;
  }
  form_point.heightFollow = val;
  // 强制触发响应式更新，确保地图组件能监听到变化
  airlineList.value = [...airlineList.value];
  if (mapRef.value) {
    mapRef.value.getPointHeght(form_point);
  }
  // 触发自动保存
  // autoSave();
};

// 处理输入框失去焦点事件
const handleBlur = (e, field) => {
  if (field === "globalHeight") {
    // 确保保留一位小数
    let value = parseFloat(e.target.value);

    // 如果值为空或无效，设置为最小值0.0
    if (isNaN(value) || e.target.value === "" || e.target.value === null) {
      value = 0.0;
    } else {
      // 限制在范围内并保留一位小数
      value = Math.max(min.value, Math.min(max.value, value));
    }

    const newHeight = parseFloat(value.toFixed(1));
    form.globalHeight = newHeight;

    // 只更新勾选了"跟随航线"的航点高度
    if (airlineList.value && airlineList.value.length > 0) {
      const updatedList = airlineList.value.map((item, index) => {
        // 创建新对象确保响应式更新，同时保留所有属性
        const newItem = {
          ...item,
          height: item.heightFollow === 1 ? newHeight : item.height
        };

        // 检查未跟随航线的航点，如果高度变得与航线高度一致，则自动勾选跟随
        // if (item.heightFollow === 0) {
        //   const heightDiff = Math.abs(item.height - newHeight);
        //   if (heightDiff < 0.01) {
        //     newItem.heightFollow = 1;
        //   }
        // }

        return newItem;
      });

      // 强制触发响应式更新
      airlineList.value = updatedList;
    }
  }

  if (field === "autoFlightSpeed") {
    let value = parseFloat(e.target.value);
    // 如果值为空或无效，设置为最小值1.0
    if (isNaN(value) || e.target.value === "" || e.target.value === null) {
      value = 1.0;
    } else {
      // 确保在速度范围内并保留一位小数
      if (value < minSpeed.value) {
        value = minSpeed.value;
      } else if (value > maxSpeed.value) {
        value = maxSpeed.value;
      }
    }
    const newSpeed = parseFloat(value.toFixed(1));
    form.autoFlightSpeed = newSpeed;

    // 只更新勾选了"跟随航线"的航点速度
    if (airlineList.value && airlineList.value.length > 0) {
      airlineList.value.forEach((item) => {
        // 只有当航点设置为跟随航线时才更新速度
        if (item.waypointSpeedFollow === 1) {
          item.waypointSpeed = newSpeed;
        }
        // 检查未跟随航线的航点，如果速度变得与航线速度一致，则自动勾选跟随
        // else if (item.waypointSpeedFollow === 0) {
        //   const speedDiff = Math.abs(item.waypointSpeed - newSpeed);
        //   if (speedDiff < 0.01) {
        //     item.waypointSpeedFollow = 1;
        //   }
        // }
      });
      // 强制触发响应式更新
      airlineList.value = [...airlineList.value];
    }
  }

  if (field === "takeOffSecurityHeight") {
    let value = parseFloat(e.target.value);

    // 如果值为空或无效，设置为默认值 1
    if (isNaN(value) || e.target.value === "" || e.target.value === null) {
      value = 1;
    } else {
      // 限制在范围内并保留一位小数
      value = Math.max(1, Math.min(500, value));
    }

    form.takeOffSecurityHeight = parseFloat(value.toFixed(1));
  }
  if (field === "globalTransitionalSpeed") {
    let value = parseFloat(parseFloat(e.target.value).toFixed(1));
    // 确保在速度范围内
    if (isNaN(value) || value < minSpeed.value) {
      value = minSpeed.value;
    } else if (value > maxSpeed.value) {
      value = maxSpeed.value;
    }
    form.globalTransitionalSpeed = value;
  }
  if (field === "globalRTHHeight") {
    let value = parseFloat(e.target.value);

    // 如果值为空或无效，设置为默认值 1
    if (isNaN(value) || e.target.value === "" || e.target.value === null) {
      value = 1;
    } else {
      // 限制在范围内并保留一位小数
      value = Math.max(1, Math.min(500, value));
    }

    form.globalRTHHeight = parseFloat(value.toFixed(1));
  }
  if (field === "height") {
    form_point.height = parseFloat(parseFloat(e.target.value).toFixed(1));
  }
  // autoSave();
};
// 改变航线高度
// const changeLineHeight = (val) => {
//   form.globalHeight = Number(val);
//   //循环airlineList.value 把高度跟随的值为1的高度设置为val
//   airlineList.value.forEach((item) => {
//     if (item.heightFollow == 1) {
//       item.height = Number(val);
//     }
//   });
//   // 强制触发响应式更新，确保地图组件能监听到变化
//   airlineList.value = [...airlineList.value];
// };
// 改变航线速度
// const changelineFlight = (val) => {
//   form.autoFlightSpeed = Number(val);
//   airlineList.value.forEach((item) => {
//     if (item.waypointSpeedFollow == 1) {
//       item.waypointSpeed = Number(val);
//     }
//   });
// };
const changeFlightaltitude = (val) => {
  // 处理空值情况，若清空则默认为0
  // val 可能是 null, undefined, '' (空字符串)
  if (val === null || val === undefined || val === "") {
    val = 0; // 设置默认值为0
  } else {
    // 如果 val 是字符串（理论上 v-model.number 会处理，但以防万一）
    if (typeof val === "string") {
      val = parseFloat(val);
    }
    // 确保 val 是一个有效数字，如果不是则设为0
    if (isNaN(val)) {
      val = 0;
    } else {
      // 保留一位小数
      val = parseFloat(val.toFixed(1));
    }
  }

  // 更新 form_point.height，确保它是一个数字
  form_point.height = val;

  // 判断是否跟随航线 - 使用精度比较
  const heightDiff = Math.abs(val - form.globalHeight);
  // console.log(heightDiff)
  // form_point.heightFollow = heightDiff < 0.01 ? 1 : 0;
  if (heightDiff != 0) {
    form_point.heightFollow = 0
  }
  // 更新 airlineList 中对应航点的数据
  if (
    airlineList.value &&
    airlineList.value[waypointIndex.value] !== undefined
  ) {
    airlineList.value[waypointIndex.value].height = val;
    airlineList.value[waypointIndex.value].heightFollow = form_point.heightFollow;
    // 强制触发响应式更新
    airlineList.value = [...airlineList.value];
  }
  if (mapRef.value) {
    mapRef.value.getPointHeght(form_point);
  }
  // 添加自动保存
  // saveline();
};
const handleFlightaltitudeBlur = (event) => {
  // 当输入框失焦时，检查其值
  // 如果是 null, undefined, 或空字符串，则设置为 0
  if (
    form_point.height === null ||
    form_point.height === undefined ||
    form_point.height === ""
  ) {
    changeFlightaltitude(0);
  }
};
// 跟随速度 飞行速度
const linespeedClick = (val) => {
  if (val == 1) {
    form_point.flightspeed = form.autoFlightSpeed;
    // 更新航点数据
    airlineList.value[waypointIndex.value].waypointSpeed = form.autoFlightSpeed;
  } else {
    // 检查defaultList是否存在且有对应索引的数据
    // if (route.query.id &&
    //   defaultList.value &&
    //   defaultList.value[waypointIndex.value] !== undefined) {
    //   form_point.flightspeed = defaultList.value[waypointIndex.value].waypointSpeed;
    //   // 更新航点数据
    //   airlineList.value[waypointIndex.value].waypointSpeed = defaultList.value[waypointIndex.value].waypointSpeed;
    // } else {
    //   // 对于新创建的航点，使用当前速度值
    //   form_point.flightspeed = airlineList.value[waypointIndex.value].waypointSpeed;
    // }
    // 设置为不跟随
    airlineList.value[waypointIndex.value].waypointSpeed = 0;
  }
  form_point.waypointSpeedFollow = val;
  airlineList.value[waypointIndex.value].waypointSpeedFollow = val;
  airlineList.value[waypointIndex.value].waypointSpeed = form_point.flightspeed;

  // 触发自动保存
  // autoSave();
};
// 高度模式
const getheightmode = (val, skipAutoSave = false) => {
  form.airlineHeightType = val;
  switch (val) {
    case 0: // 相对起飞点高度
      min.value = -1500;
      max.value = 1500;
      break;
    case 1: // 相对地面高度
      min.value = 0;
      max.value = 1500;
      break;
    case 2: // 绝对高度
      min.value = -2000;
      max.value = 10000;
      break;
    default:
      min.value = -1500;
      max.value = 1500;
  }

  // 确保当前飞行高度在新范围内
  const currentHeight = Number(form.globalHeight);
  let newHeight = currentHeight;
  if (currentHeight < min.value) {
    // newHeight = form.globalHeight = min.value;
    fnumberchange('globalHeight', min.value)
  } else if (currentHeight > max.value) {
    // newHeight = form.globalHeight = max.value;
    fnumberchange('globalHeight', max.value)
  }

  // 只更新勾选了"跟随航线"的航点高度
  if (airlineList.value && airlineList.value.length > 0) {
    const updatedList = airlineList.value.map((item, index) => {
      // 创建新对象确保响应式更新，同时保留所有属性
      const newItem = { ...item };
      // 只有当航点设置为跟随航线时才更新高度
      if (Number(item.height) < min.value) {
        newItem.height = min.value;
      } else if (Number(item.height) > max.value) {
        newItem.height = max.value;
      }
      return newItem;
    });
    // 强制触发响应式更新
    airlineList.value = updatedList;
    if (mapRef.value) {
      mapRef.value.getLineHeght(airlineList.value);
    }
  }
  // 计算飞行时长
  getflighttime(airlineList.value);

  // 只有在用户手动点击时才调用自动保存，onMounted时skipAutoSave为true，不调用
  // if (!skipAutoSave) {
  //   autoSave();
  // }
};



// 监听航线飞行速度变化，更新所有设置为"跟随航线"的航点速度
watch(
  () => form.autoFlightSpeed,
  (newSpeed, oldSpeed) => {
    // 确保新速度是有效数字
    const numericNewSpeed = Number(newSpeed);
    if (isNaN(numericNewSpeed)) return;

    // 遍历所有航点，更新设置为"跟随航线"的航点速度
    if (airlineList.value && airlineList.value.length > 0) {
      airlineList.value.forEach((item) => {
        // 只有当航点设置为跟随航线时才更新速度
        if (item.waypointSpeedFollow === 1) {
          item.waypointSpeed = numericNewSpeed;
        }
        // 检查航点速度是否与航线速度一致，如果不一致则取消跟随（使用精度比较）
        const speedDiff = Math.abs(item.waypointSpeed - numericNewSpeed);
        if (speedDiff >= 0.01) {
          item.waypointSpeedFollow = 0;
        }
      });
      // 强制触发响应式更新
      airlineList.value = [...airlineList.value];
    }
  }
);
// 获取航点设置
const getActiveName = (val) => {
  if (val == '1') {
    activeName.value = '1'
    selectedWayPoint.value = ''
  } else if (val == "2") {
    if (airlineList.value && airlineList.value.length == 0) {
      ElMessage({
        plain: true,
        message: "请先添加航点",
        type: "warning",
      });
      return;
    }
    // form_point.flightaltitude = form.flightaltitude;
    // form_point.flightspeed = form.flightspeed;
    //
    //循环更新airlineList.value 添加航点
    if (!route.query.id) {
      airlineList.value.forEach((item) => {
        if (item.waypointSpeedFollow == 1) {
          item.waypointSpeed = form.autoFlightSpeed;
        }
      });
    }
    getstopenroute(form_point.wayPointName ? form_point.wayPointName : 0);
  }
  activeName.value = val;
};
// 飞行速度
const changeFlightSpeed = (val) => {
  // 确保 val 是数字类型并保留一位小数
  let numericVal = Number(val);
  if (isNaN(numericVal)) {
    numericVal = 0;
  } else {
    // 保留一位小数并确保在有效范围内
    numericVal = Math.max(
      0,
      Math.min(maxSpeed.value, parseFloat(numericVal.toFixed(1)))
    );
  }

  // 判断是否跟随航线 - 只有当航点速度与航线速度一致时才勾选跟随（使用精度比较）
  const speedDiff = Math.abs(numericVal - form.autoFlightSpeed);
  // form_point.waypointSpeedFollow = speedDiff < 0.01 ? 1 : 0;
  if (speedDiff != 0) {
    form_point.waypointSpeedFollow = 0
  }

  // 确保设置的是数字类型
  form_point.flightspeed = numericVal;
  airlineList.value[waypointIndex.value].waypointSpeed = numericVal;
  airlineList.value[waypointIndex.value].waypointSpeedFollow =
    form_point.waypointSpeedFollow;

  // 添加自动保存
  // saveline();
  // 计算飞行时长
  getflighttime(airlineList.value);
};

// 关闭所有弹窗
const closeAllPopups = () => {
  // 关闭配置算法弹窗
  algorithmFlag.value = false;
  // 关闭配置喊话弹窗
  shoutFlag.value = false;
  // 关闭添加动作弹窗
  waypointactionFlag.value = false;
}

// 删除添加的动作
const deleteClick = (item) => {
  // console.log(form_point.actions, item)
  const index = form_point.actions.findIndex(
    (option) => option.id === item.id
  );
  if (index !== -1) {
    form_point.actions.splice(index, 1); // 删除找到的元素
  }
  airlineList.value[waypointIndex.value].actions = form_point.actions;
  // airlineList.value = [...airlineList.value];
  if (waypointactionRef.value) {
    waypointactionRef.value.setselectList(form_point.actions)
  }
  checkAction();
  // 添加自动保存
  // saveline();
}

// 拖拽排序结束回调函数
// const onEnd = (evt) => {
//   // 拖拽排序结束后触发防抖自动保存
//   debouncedAutoSave();
// };

// 保存航线设置函数
const saveline = async () => {
  // 将布尔值转换为API需要的格式：true -> 0(选中)，false -> 1(未选中)
  // const wideType = form.wideType ? 0 : 1; // 0代表选中，1代表未选中
  // const zoomType = form.zoomType ? 0 : 1; // 0代表选中，1代表未选中
  // const irType = form.irType; // 0代表选中，1代表未选中
  // const visableType = form.visableType; // 0代表选中，1代表未选中
  console.log(form)
  return;
  if (visableType == 1 && irType == 1) {
    ElMessage({
      message: "请至少选择一种照片存储类型",
      type: "warning",
    });
    return;
  }
  ElMessage({
    plain: true,
    message: "航线配置保存成功",
    type: "success",
  });
  // 关闭所有弹窗
  closeAllPopups();

  // 更新航点数据标志
  if (airlineList.value && airlineList.value.length > 0) {
    hasWaypointData.value = true;
  }

  // 如果不是初始加载，则触发防抖自动保存
  if (!isInitialLoad.value) {
    debouncedAutoSave();
  }
};
// 设置最大最小值
const actionMin = ref(0);
const actionMax = ref(0);
// 添加动作
const addClick = () => {
  // 显示动作选择界面
  waypointactionFlag.value = true;
  algorithmFlag.value = false;
  shoutFlag.value = false;
};
// 关闭添加动作
const getClose = () => {
  waypointactionFlag.value = false;
  algorithmFlag.value = false;
  shoutFlag.value = false;
};

// 算法配置
const getalgoSetting = (item) => {
  form_point.algorithmExtends = [];
  if (item) {
    form_point.algorithmExtends = item;
  }
  // 添加安全检查
  if (
    airlineList.value &&
    waypointIndex.value !== undefined &&
    waypointIndex.value !== null &&
    airlineList.value[waypointIndex.value]
  ) {
    airlineList.value[waypointIndex.value].algorithmExtendsByIds =
      form_point.algorithmExtends;
  }
  // saveline();
};
// 配置算法id集合
const getalgoView = (item) => {
  // 初始化算法
  form_point.algorithm = [];
  if (item) {
    form_point.algorithm = item;
  }
  algorithmFlag.value = false;
  // 添加安全检查
  if (
    airlineList.value &&
    waypointIndex.value !== undefined &&
    waypointIndex.value !== null &&
    airlineList.value[waypointIndex.value]
  ) {
    airlineList.value[waypointIndex.value].algorithmIds = form_point.algorithm;
  }
};
// 配置算法
const algorithmClick = () => {
  // 添加安全检查
  if (
    airlineList.value &&
    waypointIndex.value !== undefined &&
    waypointIndex.value !== null &&
    airlineList.value[waypointIndex.value]
  ) {
    algorithmList.value = airlineList.value[waypointIndex.value].algorithmIds;
    // 新增算法配置
    form_point.algorithmExtends =
      airlineList.value[waypointIndex.value].algorithmExtendsByIds;
  }
  algorithmConfig.value.algorithmExtends = form_point.algorithmExtends;
  algorithmConfig.value.algorithmList = algorithmList.value;
  algorithmFlag.value = true;
  waypointactionFlag.value = false;
  shoutFlag.value = false;
};
// 添加配置喊话
const getShoutview = (item) => {
  form_point.shout = {
    // megaphoneOperateLoop:form_point.shout.mode,
    // megaphoneType:form_point.shout.megaphoneType,
    // megaphoneOperateFile:form_point.shout.entercontent,
    // text:form_point.shout.writecontent,
    // playVolume:form_point.shout.volume,
  };
  if (item) {
    form_point.shout = item;
  }
  shoutFlag.value = false;
  // 添加安全检查
  if (
    airlineList.value &&
    waypointIndex.value !== undefined &&
    waypointIndex.value !== null &&
    airlineList.value[waypointIndex.value]
  ) {
    airlineList.value[waypointIndex.value].megaphoneOperate = form_point.shout;
  }

  // saveline();
};
// 配置喊话
const shoutClick = () => {
  // 添加安全检查
  if (
    airlineList.value &&
    waypointIndex.value !== undefined &&
    waypointIndex.value !== null &&
    airlineList.value[waypointIndex.value] &&
    airlineList.value[waypointIndex.value].megaphoneOperate
  ) {
    shoutList.value = airlineList.value[waypointIndex.value].megaphoneOperate;
  } else {
    // 如果没有现有的喊话配置，初始化一个空对象
    shoutList.value = {
      mode: 0,
      volume: 0,
      writecontent: "",
      entercontent: "",
      megaphoneType: "0",
    };
  }
  shoutFlag.value = true;
  waypointactionFlag.value = false;
  algorithmFlag.value = false;
};
// 添加动作
const getwayView = (item) => {
  if (item) {
    // 确保每个动作都有正确的最大最小值和唯一ID
    // console.log(item)
    let processedActions = item.map((action, actionIndex) => {
      const baseAction = {
        ...action,
        id: action.id || `action_${Date.now()}_${actionIndex}`, // 添加唯一ID
        // 确保actionValue是数字类型
        actionValue: (action.actionValue || action.actionValue === 0) ? Number(action.actionValue) : '',
      };

      switch (action.actionType) {
        case 1: // 悬停
          return { ...baseAction, actionMin: 1, actionMax: 900 };
        case 2: // 无人机偏航角
          return { ...baseAction, actionMin: -180, actionMax: 180 };
        case 3: // 云台俯仰角
          return { ...baseAction, actionMin: -120, actionMax: 45 };
        case 7: // 相机变焦
          return { ...baseAction, actionMin: 2, actionMax: 200 };
        case 9: // 开始等距间隔拍照
          return { ...baseAction, actionMin: 1, actionMax: 900 };
        case 10: // 开始等时间隔拍照
          return { ...baseAction, actionMin: 1, actionMax: 30 };
        default:
          return baseAction;
      }
    });
    form_point.actions = processedActions;
  }
  algorithmFlag.value = false;
  // 添加安全检查
  if (
    airlineList.value &&
    waypointIndex.value !== undefined &&
    waypointIndex.value !== null &&
    airlineList.value[waypointIndex.value]
  ) {
    airlineList.value[waypointIndex.value].actions = form_point.actions;
  }
  if (waypointactionRef.value) {
    waypointactionRef.value.setselectList(form_point.actions)
  }
  // 当航点动作更新时，重新计算飞行时长
  if (
    airlineList.value &&
    airlineList.value.length > 0 &&
    distanceArray.value &&
    distanceArray.value.length > 0
  ) {
    getflighttime(airlineList.value);
  }

  // 使用nextTick确保DOM更新后再初始化动作拖拽排序
  nextTick(() => {
    initializeActionsSortable();
    // 检查动作是否需要警告
    checkAction()
  });
  // saveline();
};

// 首次设置起飞点
const oneSetTakeoffMode = () => {
  // 直接把绘制模式切换为 起飞点绘制
  draw_mode.value = 1
  if (mapRef.value) {
    mapRef.value.enterSetTakeoffMode();
  }
  // map.value.getContainer().style.cursor = "crosshair"; // 设置鼠标样式
  // const draw_mode = ref(1); //1 起飞点绘制 2 航线绘制 3不绘制
  // const is_has_takeOffRefPoint = ref(false); // 是否有起飞点(为了方便显示)
  // flayoneShow.value = val;
  // 更新起飞点标志
  // hasTakeoffPoint.value = !val; // false表示已设置起飞点，true表示未设置
  // 如果起飞点已设置且不是初始加载，则触发防抖自动保存
  // if (!val && !isInitialLoad.value) {
  //   debouncedAutoSave();
  // }
  // if (!val && !isInitialLoad.value) {
  //   debouncedAutoSave();
  // }
};

// 进入重设起飞点模式
const enterResetTakeoffMode = () => {
  isResettingTakeoff.value = true;
  // flayShow.value = false; // 设置为false进入重设模式
  // 通知地图组件进入重设模式
  if (mapRef.value) {
    mapRef.value.enterSetTakeoffMode();
  }
};
// 取消重设起飞点模式
const cancelResetTakeoffMode = () => {
  isResettingTakeoff.value = false;
  // flayShow.value = true; // 设置为true退出重设模式
  // 通知地图组件退出重设模式
  if (mapRef.value) {
    mapRef.value.exitSetTakeoffMode();
  }
};

// 在组件卸载前清理sortable实例
onBeforeUnmount(() => {
  if (actionsContainer.value && actionsContainer.value.sortableInstance) {
    try {
      actionsContainer.value.sortableInstance.destroy();
    } catch (e) {
      console.log("Error destroying sortable instance:", e);
    }
    actionsContainer.value.sortableInstance = null;
  }
});

// 初始化动作拖拽排序
const initializeActionsSortable = async () => {
  // 等待DOM更新完成
  await nextTick();

  // 确保容器存在
  if (actionsContainer.value) {
    // 先销毁已存在的sortable实例（如果有的话）
    if (actionsContainer.value.sortableInstance) {
      try {
        actionsContainer.value.sortableInstance.destroy();
      } catch (e) {
        console.log("Error destroying sortable instance:", e);
      }
      actionsContainer.value.sortableInstance = null;
    }

    // 检查容器中是否有子元素
    const children = actionsContainer.value.children;

    // 确保有足够的元素才初始化拖拽
    if (children.length < 1) {
      // console.log("No items for sorting, skipping initialization");
      return;
    }

    try {
      // 创建Sortable实例
      const sortable = new Sortable(actionsContainer.value, {
        animation: 150,
        ghostClass: "sortable-ghost",
        chosenClass: "sortable-chosen",
        dragClass: "sortable-drag",
        handle: ".sortable-handle", // 只在特定元素上触发拖拽
        // onStart: (evt) => {
        //   console.log("Actions at start:", JSON.stringify(form_point.actions));
        // },
        onEnd: (evt) => {
          // 拖拽结束时更新数据
          const { oldIndex, newIndex } = evt;

          // 确保索引有效
          if (
            oldIndex !== undefined &&
            newIndex !== undefined &&
            oldIndex !== newIndex &&
            oldIndex < form_point.actions.length &&
            newIndex < form_point.actions.length
          ) {
            // 创建新的动作数组副本
            const newActions = [...form_point.actions];

            // 重新排列数组
            const movedItem = newActions.splice(oldIndex, 1)[0];
            newActions.splice(newIndex, 0, movedItem);

            // 更新form_point.actions
            form_point.actions = newActions;

            // 更新航点动作
            if (airlineList.value && airlineList.value[waypointIndex.value]) {
              airlineList.value[waypointIndex.value].actions = [...newActions];
              // 强制触发响应式更新
              airlineList.value = [...airlineList.value];
            }
            checkAction();
            if (waypointactionRef.value) {
              waypointactionRef.value.setselectList(form_point.actions)
            }
            // 添加自动保存
            // saveline();
          } else {
            // console.log(
            //   "Invalid drag operation:",
            //   oldIndex,
            //   newIndex,
            //   form_point.actions.length
            // );
          }
        },
      });

      // 保存sortable实例引用，以便后续销毁
      actionsContainer.value.sortableInstance = sortable;
      return sortable;
    } catch (error) {
      console.error("Failed to initialize Sortable:", error);
    }
  }
};
// 获取起飞点数据
const getstartdata = (data) => {
  startdata.value.point = data.point
}
// 补的监听赋值方法
watch(form_point, (newform) => {
  if (!form_point.wayPointName && form_point.wayPointName != 0) return;
  if (!newform.wayPointName && newform.wayPointName != 0) return;
  airlineList.value[form_point.wayPointName].actions = newform.actions // 航点动作
  // airlineList.value[form_point.wayPointName].segmentActions = newform.segmentActions // 航段动作
  airlineList.value[form_point.wayPointName].longitude = newform.longitude // 经度
  airlineList.value[form_point.wayPointName].latitude = newform.latitude // 纬度
  airlineList.value[form_point.wayPointName].height = newform.height // 飞行高度
  airlineList.value[form_point.wayPointName].heightFollow = newform.heightFollow // 飞行高度 是否跟随航线
  airlineList.value[form_point.wayPointName].flightspeed = newform.flightspeed // 飞行速度
  airlineList.value[form_point.wayPointName].waypointSpeedFollow = newform.waypointSpeedFollow // 飞行速度 是否跟随航线
  airlineList.value[form_point.wayPointName].attitudeHead = newform.attitudeHead // 无人机偏航角
  airlineList.value[form_point.wayPointName].imageFormat = newform.imageFormat // 镜头模式
  airlineList.value[form_point.wayPointName].positionType = newform.positionType // 地图类型
  // ai和喊话不在这赋值
  // console.log(airlineList.value)
})
// 获取所有航线数据
// 新_ 在添加，编辑，删除航点时触发
const getallData = (data) => {
  if (!data || !data.type) {
    console.log(data)
    return false
  }
  if (data.type == 'add') {
    if (airlineList.value.length == data.allData.points.length - 1) {
      let dindex = data.allData.points.length - 1
      airlineList.value.push({
        index: Number(dindex),
        wayPointName: `航点${dindex + 1}`,
        actions: [],// 航点动作
        segmentActions: [],// 航段动作
        algorithmIds: [],//好像是ai
        algorithmExtendsByIds: [],//好像是ai
        megaphoneOperate: {},//喊话
        positionType: 2, // 地图类型
        imageFormat: 0, // 镜头模式
        attitudeHead: 0, //偏航角
        waypointSpeed: form.autoFlightSpeed, //速度
        height: data.allData.points[dindex][2], // 高度
        heightFollow: 1,// 飞行高度 是否跟随航线
        waypointSpeedFollow: 1,// 飞行速度 是否跟随航线
        longitude: data.allData.points[dindex][0],
        latitude: data.allData.points[dindex][1],
      })
      set_segmentActions();
    }
  }
  if (data.type == 'drag') {
    let i = data.index
    airlineList.value[i].longitude = data.allData.points[i][0]
    airlineList.value[i].latitude = data.allData.points[i][1]
    airlineList.value[i].height = data.allData.points[i][2]
  }
  if (data.type == 'del') {
    airlineList.value.splice(data.index, 1);
    for (let i in airlineList.value) {
      airlineList.value[i].index = Number(i)
      airlineList.value[i].wayPointName = `航点${Number(i) + 1}`
    }
    if (form_point.wayPointName == data.index) {
      getActiveName('1');
      getClose();
    } else if (form_point.wayPointName > data.index) {
      form_point.wayPointName = form_point.wayPointName - 1
      let newform = airlineList.value[form_point.wayPointName]
      form_point.actions = newform.actions
      form_point.segmentActions = newform.segmentActions
      form_point.longitude = newform.longitude
      form_point.latitude = newform.latitude
      form_point.height = newform.height
      form_point.heightFollow = newform.heightFollow
      form_point.flightspeed = newform.flightspeed
      form_point.waypointSpeedFollow = newform.waypointSpeedFollow
      form_point.attitudeHead = newform.attitudeHead
      form_point.imageFormat = newform.imageFormat
      form_point.positionType = newform.positionType
    }
    waypointIndex.value = form_point.wayPointName
    if (waypointactionRef.value) {
      waypointactionRef.value.setselectList(form_point.actions)
    }
    // console.log(form_point.wayPointName, airlineList.value)
    checkAction();//更新动作的检测提示
    // if (waypointIndex.value) {
    //   const waypointData = airlineList.value.find((item) => item.index == waypointIndex.value);
    //   selectedWayPoint.value = waypointData;
    // }
    // console.log(airlineList.value)
  }
  gaodeList.value = airlineList.value.map((item) => ({
    longitude: item.longitude,
    latitude: item.latitude,
  }));
  getflighttime(airlineList.value);
  // // 保存现有的航点动作数据
  // // return;
  // const existingActions = airlineList.value
  //   ? airlineList.value.map((waypoint) => ({
  //     actions: waypoint.actions || [],
  //     algorithmIds: waypoint.algorithmIds || [],
  //     algorithmExtendsByIds: waypoint.algorithmExtendsByIds || [],
  //     megaphoneOperate: waypoint.megaphoneOperate || {},
  //     positionType: waypoint.positionType || 2,
  //     imageFormat: waypoint.imageFormat || 0,
  //     attitudeHead: waypoint.attitudeHead || 0,
  //     waypointSpeed: waypoint.waypointSpeed || 10,
  //     height: waypoint.height || 100,
  //     heightFollow: waypoint.heightFollow,
  //     waypointSpeedFollow: waypoint.waypointSpeedFollow,
  //   }))
  //   : [];
  // // 添加obj所有属性
  // airlineList.value = Array(val.points.length)
  //   .fill()
  //   .map((_, index) => {
  //     // 使用深拷贝创建基础对象
  //     const newObj = {
  //       ...JSON.parse(JSON.stringify(obj)),
  //       index,
  //       wayPointName: `航点${index + 1}`
  //     };

  //     // 设置坐标数据
  //     if (index < val.points.length) {
  //       const [longitude, latitude, height] = val.points[index];
  //       newObj.longitude = longitude;
  //       newObj.latitude = latitude;
  //       newObj.height = height;
  //     }

  //     // 处理动作数据
  //     const existingAction = existingActions[index];
  //     if (existingAction) {
  //       // 提取需要复用的属性
  //       const { actions, algorithmIds, algorithmExtendsByIds, megaphoneOperate,
  //         positionType, imageFormat, attitudeHead, waypointSpeed,
  //         heightFollow, waypointSpeedFollow } = existingAction;

  //       Object.assign(newObj, {
  //         actions,
  //         algorithmIds,
  //         algorithmExtendsByIds,
  //         megaphoneOperate,
  //         positionType,
  //         imageFormat,
  //         attitudeHead,
  //         waypointSpeed,
  //         heightFollow,
  //         waypointSpeedFollow
  //       });
  //     } else {
  //       // 新航点的默认设置
  //       const heightDiff = Math.abs(newObj.height - form.globalHeight);
  //       const speedDiff = Math.abs(newObj.waypointSpeed - form.autoFlightSpeed);

  //       newObj.heightFollow = heightDiff < 0.01 ? 1 : 0;
  //       newObj.waypointSpeedFollow = speedDiff < 0.01 ? 1 : 0;
  //     }

  //     return newObj;
  //   });
  // // 更新航点数据标志
  // hasWaypointData.value = airlineList.value && airlineList.value.length > 0;

  // // 当航点数据更新时，重新计算飞行时长
  // if (
  //   airlineList.value &&
  //   airlineList.value.length > 0 &&
  //   distanceArray.value &&
  //   distanceArray.value.length > 0
  // ) {
  //   getflighttime(airlineList.value);
  // }

  // // 如果defaultList.value有值，则赋值给airlineList.value
  // if (
  //   defaultList.value &&
  //   defaultList.value.length > 0 &&
  //   defaultList.value.length >= airlineList.value.length
  // ) {
  //   //  defaultList waypointSpeed attitudeHead赋值给airlineList.value
  //   airlineList.value.forEach((item) => {
  //     item.attitudeHead = defaultList.value[item.index].attitudeHead; // 偏航角
  //     item.imageFormat = defaultList.value[item.index].imageFormat; // 镜头模式
  //     item.waypointSpeed = defaultList.value[item.index].waypointSpeed; // 速度
  //     item.heightFollow = defaultList.value[item.index].heightFollow; // 跟随航线高度
  //     item.positionType = defaultList.value[item.index].positionType; // 地图
  //     item.actions = defaultList.value[item.index].actions; // 动作
  //     item.waypointSpeedFollow =
  //       defaultList.value[item.index].waypointSpeedFollow; // 跟随航线速度
  //   });
  // } else {
  //   // 获取最后一个航点的索引
  //   const lastIndex = airlineList.value.length - 1;
  //   if (lastIndex >= 0) {
  //     // 修改最后一个航点的参数
  //     // 根据高度和速度是否相等设置跟随状态（使用精度比较）
  //     const heightDiff = Math.abs(airlineList.value[lastIndex].height - form.globalHeight);
  //     const speedDiff = Math.abs(airlineList.value[lastIndex].waypointSpeed - form.autoFlightSpeed);

  //     airlineList.value[lastIndex] = {
  //       ...airlineList.value[lastIndex],
  //       attitudeHead: 0, // 偏航角
  //       imageFormat: 0, // 镜头模式
  //       waypointSpeed: form.autoFlightSpeed, // 速度
  //       heightFollow: heightDiff < 0.01 ? 1 : 0, // 跟随航线高度
  //       positionType: 2, // 地图
  //       waypointSpeedFollow: speedDiff < 0.01 ? 1 : 0, // 跟随航线速度
  //     };
  //   }
  // }

  // //保留默认高德数据
  // gaodeList.value = airlineList.value.map((item) => ({
  //   longitude: item.longitude,
  //   latitude: item.latitude,
  // }));
  // if (activeName.value == "2") {
  //   getstopenroute(form_point.wayPointName);
  // }
  // showDataloading.value = true; //刷新状态
  // if (activeName.value == "2") {
  //   if (airlineList.value && airlineList.value.length > 0) {
  //     getstopenroute(0);
  //   } else {
  //     activeName.value = "1";
  //   }
  // }
  // setTimeout(() => {
  //   showDataloading.value = false; //刷新状态
  //   // 当航点数据更新时，重新初始化拖拽功能
  //   if (
  //     activeName.value == "2" &&
  //     airlineList.value &&
  //     airlineList.value.length > 0
  //   ) {
  //     nextTick(() => {
  //       setTimeout(() => {
  //         initializeActionsSortable();
  //       }, 200);
  //     });
  //   }
  // }, 300);

  // 如果不是初始加载且有航点数据，则触发防抖自动保存（优化：只调用一次）
  // if (!isInitialLoad.value && hasWaypointData.value) {
  //   debouncedAutoSave();
  // }
};
// 获取总距离
const gettotalDistance = (val) => {
  form.totalDistance = val;
};
// 获取航点名称
const getstopenroute = async (val) => {
  // if (showDataloading.value) return;
  // showDataloading.value = true; //刷新状态
  airlineClick(val); //更新边选中
  waypointIndex.value = val;
  form_point.longitude = airlineList.value[waypointIndex.value].longitude;
  form_point.latitude = airlineList.value[waypointIndex.value].latitude;
  form_point.positionType = airlineList.value[waypointIndex.value].positionType;
  form_point.imageFormat = airlineList.value[waypointIndex.value].imageFormat;
  form_point.attitudeHead = airlineList.value[waypointIndex.value].attitudeHead;
  form_point.heightFollow = airlineList.value[waypointIndex.value].heightFollow;
  form_point.waypointSpeedFollow = airlineList.value[waypointIndex.value].waypointSpeedFollow;
  form_point.segmentActions = airlineList.value[waypointIndex.value].segmentActions;
  // 根据当前航点值与航线设置值是否相等来设置跟随状态（使用精度比较）
  const heightDiff = Math.abs(airlineList.value[waypointIndex.value].height - form.globalHeight);
  const speedDiff = Math.abs(airlineList.value[waypointIndex.value].waypointSpeed - form.autoFlightSpeed);
  // form_point.heightFollow = heightDiff < 0.01 ? 1 : 0;
  // console.log(heightDiff)
  if (heightDiff != 0) {
    form_point.heightFollow = 0
  }
  form_point.waypointSpeedFollow = speedDiff < 0.01 ? 1 : 0;
  // 处理动作数据，确保有正确的最大最小值
  const actions = airlineList.value[waypointIndex.value].actions;
  if (actions && Array.isArray(actions)) {
    // 如果有动作数据，处理最大最小值
    const processedActions = actions.map((action) => {
      // 确保actionValue是数字类型并保留一位小数（如果需要）
      const needDecimal = [2, 3, 7, 9].includes(action.actionType);
      const processedAction = {
        ...action,
        actionValue: needDecimal
          ? parseFloat(truncateToDecimalPlaces(Number(action.actionValue), 1))
          : Number(action.actionValue),
        actionMin: Number(action.actionMin),
        actionMax: Number(action.actionMax),
      };

      switch (action.actionType) {
        case 1: // 悬停
          return { ...processedAction, actionMin: 1, actionMax: 900 };
        case 2: // 无人机偏航角
          return { ...processedAction, actionMin: -180, actionMax: 180 };
        case 3: // 云台俯仰角
          return { ...processedAction, actionMin: -120, actionMax: 45 };
        case 7: // 相机变焦
          return { ...processedAction, actionMin: 2, actionMax: 200 };
        case 9: // 开始等距间隔拍照
          return { ...processedAction, actionMin: 1, actionMax: 900 };
        case 10: // 开始等时间隔拍照
          return { ...processedAction, actionMin: 1, actionMax: 30 };
        default:
          return processedAction;
      }
    });
    form_point.actions = processedActions;
  } else {
    form_point.actions = [];
    // 将空动作数组保存到航点数据中
    airlineList.value[waypointIndex.value].actions = [];
  }
  if (waypointactionRef.value) {
    waypointactionRef.value.setselectList(form_point.actions)
  }
  form_point.flightspeed = airlineList.value[waypointIndex.value].waypointSpeed;
  form_point.height = airlineList.value[waypointIndex.value].height;
  form_point.algorithm = airlineList.value[waypointIndex.value].algorithmIds;
  form_point.shout = airlineList.value[waypointIndex.value].megaphoneOperate;
  form_point.algorithmExtends =
    airlineList.value[waypointIndex.value].algorithmExtendsByIds;

  // 编辑的时候
  if (route.query.id) {
    if (form_point.positionType !== 2) {
      const option = await coordinateData({
        longitude: gaodeList.value[waypointIndex.value].longitude,
        latitude: gaodeList.value[waypointIndex.value].latitude,
        method: "wgs84ToGcj02",
      });
      form_point.longitude = parseFloat(option.longitude.toFixed(12));
      form_point.latitude = parseFloat(option.latitude.toFixed(12));
    } else {
      form_point.longitude = gaodeList.value[waypointIndex.value].longitude;
      form_point.latitude = gaodeList.value[waypointIndex.value].latitude;
    }
  }

  setTimeout(() => {
    console.log
    showDataloading.value = false; //刷新状态
    // 使用nextTick确保DOM更新后再初始化动作拖拽排序
    nextTick(() => {
      setTimeout(() => {
        initializeActionsSortable();
      }, 200);
    });
  }, 300);
};

const getWayPointName = (index) => {
  const wayPoint = airlineList.value.find((item) => item.index === index);
  return wayPoint ? wayPoint.wayPointName : "";
};

// 保存航点设置
const saveList = () => {
  // const wayPointName = getWayPointName(form_point.wayPointName);
  // if (!wayPointName) {
  //   ElMessage({
  //     plain: true,
  //     message: "请先添加航点",
  //     type: "warning",
  //   });
  //   return;
  // }
  saveAllEdit(false);
  return;
  try {
    // 检查airlineList和waypointIndex是否有效
    if (
      !airlineList.value ||
      !Array.isArray(airlineList.value) ||
      waypointIndex.value === undefined ||
      waypointIndex.value === null
    ) {
      console.error("无效的参数:", {
        airlineList: airlineList.value,
        waypointIndex: waypointIndex.value,
      });
      return;
    }

    // 检查索引是否在有效范围内
    if (
      waypointIndex.value < 0 ||
      waypointIndex.value >= airlineList.value.length
    ) {
      console.error("索引超出范围:", waypointIndex.value);
      return;
    }

    // 获取当前航点对象
    const currentWaypoint = airlineList.value[waypointIndex.value];
    if (!currentWaypoint) {
      console.error("航点对象不存在:", waypointIndex.value);
      return;
    }

    // 更新航点属性
    currentWaypoint.positionType = form_point.positionType;
    currentWaypoint.waypointSpeed = form_point.flightspeed;
    currentWaypoint.imageFormat = form_point.imageFormat;
    currentWaypoint.attitudeHead = form_point.attitudeHead;
    currentWaypoint.heightFollow = form_point.heightFollow;
    currentWaypoint.waypointSpeedFollow = form_point.waypointSpeedFollow;
    currentWaypoint.algorithmIds = form_point.algorithm
      ? [...form_point.algorithm]
      : [];
    currentWaypoint.algorithmExtends = form_point.algorithmExtends
      ? [...form_point.algorithmExtends]
      : [];
    // 安全处理actions数组
    currentWaypoint.actions = form_point.actions ? [...form_point.actions] : [];

    // 处理megaphoneOperate对象
    if (form_point.shout && typeof form_point.shout === "object") {
      currentWaypoint.megaphoneOperate.megaphoneOperateLoop =
        form_point.shout.megaphoneOperateLoop;
      currentWaypoint.megaphoneOperate.megaphoneType =
        form_point.shout.megaphoneType;
      currentWaypoint.megaphoneOperate.megaphoneOperateFile =
        form_point.shout.megaphoneOperateFile;
      currentWaypoint.megaphoneOperate.text = form_point.shout.text;
      currentWaypoint.megaphoneOperate.playVolume = form_point.shout.playVolume;
    }
    // 飞行时长
    getflighttime(airlineList.value);
  } catch (error) {
    console.error("保存航点数据时出错:", error);
  }
  defaultList.value = JSON.parse(JSON.stringify(airlineList.value));
  // console.log(airlineList.value, "保存某个航点");
  ElMessage({
    plain: true,
    message: wayPointName + "保存成功",
    type: "success",
  });
  // 关闭所有弹窗
  closeAllPopups();

  // 使用nextTick确保DOM更新后再初始化拖拽功能
  nextTick(() => {
    setTimeout(() => {
      initializeActionsSortable();
    }, 200);
  });
  // 使用防抖自动保存优化航点保存调用
  debouncedAutoSave();
};

// 添加一个专门用于直播镜头模式变更的函数
const updateImageFormat = () => {
  // 更新航点数据
  if (airlineList.value && airlineList.value[waypointIndex.value]) {
    airlineList.value[waypointIndex.value].imageFormat = form_point.imageFormat;
  }

  // saveline();
};

// 保存数据
const updatemap = async () => {
  let method = "";
  if (form_point.positionType == 0) {
    method = "gcj02ToWgs84";
  } else if (form_point.positionType == 1) {
    method = "gcj02ToBd09";
  } else if (form_point.positionType == 3) {
    method = "gcj02ToCgcs2000";
  } else {
    method = "";
  }
  airlineList.value[waypointIndex.value].positionType = form_point.positionType;
  if (form_point.positionType !== 2) {
    //更改坐标
    try {
      const option = await coordinateData({
        longitude: gaodeList.value[waypointIndex.value].longitude,
        latitude: gaodeList.value[waypointIndex.value].latitude,
        method: method,
      });
      form_point.longitude = option.longitude.toFixed(12);
      form_point.latitude = option.latitude.toFixed(12);
      //更新经纬度
      airlineList.value.forEach((item) => {
        item.longitude = Number(option.longitude.toFixed(12));
        item.latitude = Number(option.latitude.toFixed(12));
      });
    } catch (error) {
      console.error("坐标转换失败:", error);
    }
  } else {
    form_point.longitude = gaodeList.value[waypointIndex.value].longitude;
    form_point.latitude = gaodeList.value[waypointIndex.value].latitude;
    //更新经纬度
    airlineList.value.forEach((item) => {
      item.longitude = gaodeList.value[waypointIndex.value].longitude;
      item.latitude = gaodeList.value[waypointIndex.value].latitude;
    });
  }

  // saveline();
};

// 保存编辑的航线名称
const saveAirlineNameEdit = async () => {
  try {
    const params = {
      id: route.query.id,
      airlineName: ruleForm.airlineNameData,
      airlineType: route.query.airlineType,
      brandId: form.brandId,
      seriesId: form.seriesId,
      modelId: form.modelId,
    };

    const response = await editName(params);

    // 检查响应状态
    if (response.code === 200) {
      ElMessage.success("航线名称保存成功");
      form.airlineName = ruleForm.airlineNameData || "";
      showEditAirlineName.value = false;
    } else {
      // 接口返回业务错误
      const errorMsg = response.message || response.msg || "保存失败";
      ElMessage.error(errorMsg);
    }
  } catch (err) {
    // 处理HTTP错误
    if (err.response) {
      const { status, data } = err.response;
      let errorMsg = "操作失败";

      if (status === 500) {
        errorMsg = data?.message || data?.msg || "服务器内部错误";
      } else if (status === 404) {
        errorMsg = "接口不存在";
      } else if (status === 403) {
        errorMsg = "权限不足";
      } else if (status === 401) {
        errorMsg = "未授权访问";
      } else {
        errorMsg = data?.message || data?.msg || `请求失败 (${status})`;
      }

      ElMessage.error(errorMsg);
    } else if (err.request) {
      // 网络错误
      ElMessage.error("网络连接失败，请检查网络设置");
    } else {
      // 其他错误
      ElMessage.error(err.message || "操作失败");
    }
  }
};

// 保存新增的航线名称（在本地保存，实际会在保存航线时一起提交）
const saveAirlineNameAdd = async () => {
  try {
    const params = {
      airlineName: ruleForm.airlineNameData,
      airlineType: route.query.airlineType,
      brandId: form.brandId,
      seriesId: form.seriesId,
      modelId: form.modelId,
    };

    const response = await addName(params);

    // 检查响应状态
    if (response.code === 200) {
      ElMessage.success("航线名称保存成功");
    } else {
      // 接口返回业务错误
      const errorMsg = response.message || response.msg || "保存失败";
      ElMessage.error(errorMsg);
    }
  } catch (err) {
    // 处理HTTP错误
    if (err.response) {
      const { status, data } = err.response;
      let errorMsg = "操作失败";

      if (status === 500) {
        errorMsg = data?.message || data?.msg || "服务器内部错误";
      } else if (status === 404) {
        errorMsg = "接口不存在";
      } else if (status === 403) {
        errorMsg = "权限不足";
      } else if (status === 401) {
        errorMsg = "未授权访问";
      } else {
        errorMsg = data?.message || data?.msg || `请求失败 (${status})`;
      }

      ElMessage.error(errorMsg);
    } else if (err.request) {
      // 网络错误
      ElMessage.error("网络连接失败，请检查网络设置");
    } else {
      // 其他错误
      ElMessage.error(err.message || "操作失败");
    }
  }
};

// let wideType = 0;
// let zoomType = 0;
let irType = 0;
let visableType = 0;
const isSuccess = ref(false);
const saveAll = async () => {
  isSuccess.value = false;
  if (!is_has_takeOffRefPoint.value) {
    //没有设置起飞点
    ElMessage.error("请设置起飞点");
    return;
  }

  // 将布尔值转换为API需要的格式：true -> 0(选中)，false -> 1(未选中)
  // const wideType = form.wideType ? 0 : 1; // 0代表选中，1代表未选中
  // const zoomType = form.zoomType ? 0 : 1; // 0代表选中，1代表未选中
  const irType = form.irType; // 0代表选中，1代表未选中
  const visableType = form.visableType; // 0代表选中，1代表未选中
  if (visableType == 1 && irType == 1) {
    ElMessage({
      message: "请至少选择一种照片存储类型",
      type: "warning",
    });
    return;
  }

  const takeOffRefPoint = startdata.value.point.toString()
  // 深拷贝，避免响应式对象导致的循环引用
  const wayPoints = JSON.parse(JSON.stringify(airlineList.value));
  if (gaodeList.value && gaodeList.value.length > 0) {
    const gaodeData = JSON.parse(JSON.stringify(gaodeList.value));
    wayPoints.forEach((item, index) => {
      item.longitude = gaodeData[index].longitude;
      item.latitude = gaodeData[index].latitude;

      // 如果heightFollow为undefined，则默认设置为1
      if (item.heightFollow === undefined) {
        item.heightFollow = 1;
      }

      // 如果waypointSpeedFollow为undefined，则默认设置为1
      if (item.waypointSpeedFollow === undefined) {
        item.waypointSpeedFollow = 1;
      }
    });
  }
  const time = formattedTotalTime.value;
  const params = {
    airlineName: ruleForm.airlineNameData, //form.airlineName,
    airlineType: route.query.airlineType,
    brandId: form.brandId, // 使用form中的brandId
    seriesId: form.seriesId, // 使用form中的seriesId
    modelId: form.modelId, // 使用form中的modelId
    // wideType: wideType, //广角照片
    // zoomType: zoomType, //变焦照片
    wideType: 1, //广角照片
    zoomType: 1, //变焦照片
    irType: irType, //红外照片
    visableType: visableType, //可见光照片
    airlineHeightType: form.airlineHeightType, //航线高度模式
    globalHeight: form.globalHeight, //飞行高度
    autoFlightSpeed: form.autoFlightSpeed, //飞行速度
    globalTransitionalSpeed: form.globalTransitionalSpeed, //起飞速度
    attitudeHead: form.attitudeHead, //无人机偏航角
    wayPointType: form.wayPointType, //航点类型
    outOfControlAction: form.outOfControlAction, //无人机失控动作
    finishAction: form.finishAction, //无人机完成动作
    takeOffSecurityHeight: form.takeOffSecurityHeight, //安全起飞高度
    globalRTHHeight: form.globalRTHHeight, //返航高度
    pointNum: airlineList.value.length,
    executeTime: time,
    totalDistance: form.totalDistance,
    wayPoints,
    takeOffRefPoint: takeOffRefPoint,
  };

  try {
    await ruleFormRef.value?.validate();
    const response = await add(params);
    // 检查响应状态
    if (response.code === 200) {
      ElMessage.success("保存成功");
      isSuccess.value = true;
      // 关闭所有弹窗
      closeAllPopups();
      // 返回列表
      router.go(-1);
    } else {
      // 接口返回业务错误
      const errorMsg = response.message || response.msg || "保存失败";
      ElMessage.error(errorMsg);
    }
  } catch (err) {
    // 处理HTTP错误（如500、404等）
    if (err.response) {
      const { status, data } = err.response;
      let errorMsg = "操作失败";

      if (status === 500) {
        errorMsg = data?.message || data?.msg || "服务器内部错误";
      } else if (status === 404) {
        errorMsg = "接口不存在";
      } else if (status === 403) {
        errorMsg = "权限不足";
      } else if (status === 401) {
        errorMsg = "未授权访问";
      } else {
        errorMsg = data?.message || data?.msg || `请求失败 (${status})`;
      }

      ElMessage.error(errorMsg);
    } else if (err.request) {
      // 网络错误
      ElMessage.error("网络连接失败，请检查网络设置");
    } else {
      // 其他错误
      ElMessage.error(err.message || "操作失败");
    }
  }
};
const updateyaw = () => {
  airlineList.value[waypointIndex.value].attitudeHead = form_point.attitudeHead;

  // saveline();
};

// 更新航点坐标
const updateWaypointCoordinates = async () => {
  try {
    // 验证当前航点索引是否有效
    if (
      waypointIndex.value === undefined ||
      waypointIndex.value === null ||
      waypointIndex.value < 0 ||
      waypointIndex.value >= airlineList.value.length
    ) {
      console.error("无效的航点索引:", waypointIndex.value);
      return;
    }
    // 验证经纬度格式
    const longitude = parseFloat(form_point.longitude);
    const latitude = parseFloat(form_point.latitude);

    if (isNaN(longitude) || isNaN(latitude)) {
      console.error("经纬度格式无效");
      return;
    }
    // 验证经纬度范围
    if (longitude < -180 || longitude > 180) {
      ElMessage.error("经度范围应在-180~180之间");
      return;
    }
    if (latitude < -90 || latitude > 90) {
      ElMessage.error("纬度范围应在-90~90之间");
      return;
    }

    if (form_point.positionType == 0) {
      //如果是84
      const option = await coordinateData({
        longitude: longitude,
        latitude: latitude,
        method: "wgs84ToGcj02",
      });
      //更新高德的数组
      gaodeList.value[waypointIndex.value].longitude = Number(
        option.longitude.toFixed(12)
      );
      gaodeList.value[waypointIndex.value].latitude = Number(
        option.latitude.toFixed(12)
      );
    } else if (form_point.positionType == 1) {
      //如果是百度
      const option = await coordinateData({
        longitude: longitude,
        latitude: latitude,
        method: "bd09ToGcj02",
      });
      //更新高德的数组
      gaodeList.value[waypointIndex.value].longitude = Number(
        option.longitude.toFixed(12)
      );
      gaodeList.value[waypointIndex.value].latitude = Number(
        option.latitude.toFixed(12)
      );
    } else if (form_point.positionType == 3) {
      //如果是cgcs2000
      const option = await coordinateData({
        longitude: longitude,
        latitude: latitude,
        method: "cgcs2000ToGcj02",
      });
      //更新高德的数组
      gaodeList.value[waypointIndex.value].longitude = Number(
        option.longitude.toFixed(12)
      );
      gaodeList.value[waypointIndex.value].latitude = Number(
        option.latitude.toFixed(12)
      );
    } else {
      gaodeList.value[waypointIndex.value].longitude = Number(longitude);
      gaodeList.value[waypointIndex.value].latitude = Number(latitude);
    }

    // 更新地图上的航点位置
    updateMapWaypointPosition(
      gaodeList.value[waypointIndex.value].longitude,
      gaodeList.value[waypointIndex.value].latitude
    );

    // 更新航点数据
    if (airlineList.value && airlineList.value[waypointIndex.value]) {
      airlineList.value[waypointIndex.value].longitude = gaodeList.value[waypointIndex.value].longitude;
      airlineList.value[waypointIndex.value].latitude = gaodeList.value[waypointIndex.value].latitude;
    }

    // 显示成功消息
    ElMessage.success(`航点${waypointIndex.value + 1}坐标已更新`);

    // saveline();
  } catch (error) {
    console.error("更新航点坐标时出错:", error);
    ElMessage.error("更新航点坐标失败");
  }
};

// 验证坐标格式
const validateCoordinate = () => {
  const longitude = parseFloat(form_point.longitude);
  const latitude = parseFloat(form_point.latitude);

  // 实时验证经纬度格式
  if (
    form_point.longitude &&
    (isNaN(longitude) || longitude < -180 || longitude > 180)
  ) {
    // 可以在这里添加实时提示
    console.warn("经度格式或范围不正确");
  }

  if (
    form_point.latitude &&
    (isNaN(latitude) || latitude < -90 || latitude > 90)
  ) {
    // 可以在这里添加实时提示
    console.warn("纬度格式或范围不正确");
  }
};

// 更新地图上的航点位置
const updateMapWaypointPosition = (longitude, latitude) => {
  // 调用地图组件的方法更新航点位置
  if (mapRef.value && mapRef.value.updateWaypointCoordinate) {
    mapRef.value.updateWaypointCoordinate(
      waypointIndex.value,
      longitude,
      latitude
    );
  } else {
    console.warn("地图组件未初始化或方法不可用");
  }
  // 更新航点位置后触发防抖自动保存
  // debouncedAutoSave();
};

// 地图组件引用
const mapRef = ref(null);
//二次确认
const savetwo = async (val) => {
  // console.log(form)
  // 将布尔值转换为API需要的格式：true -> 0(选中)，false -> 1(未选中)
  // const wideType = form.wideType ? 0 : 1; // 0代表选中，1代表未选中
  // const zoomType = form.zoomType ? 0 : 1; // 0代表选中，1代表未选中
  const irType = form.irType; // 0代表选中，1代表未选中
  const visableType = form.visableType; // 0代表选中，1代表未选中
  if (visableType == 1 && irType == 1) {
    ElMessage({
      message: "请至少选择一种照片存储类型",
      type: "warning",
    });
    return;
  }
  // 检查航线名称是否已填写
  if (!ruleForm.airlineNameData || ruleForm.airlineNameData.trim() === "") {
    ElMessage({
      message: "请填写航线名称",
      type: "warning",
    });
    return;
  }

  let message = "是否确认保存当前数据并退出？";
  // if (val == "saveAllEdit" || val == "saveAll") {
  //   message = "是否确认保存当前数据并退出？";
  // } else {
  // }
  try {
    await ElMessageBox.confirm(message, "保存确认", {
      type: "success",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      beforeClose: async (action, instance, done) => {
        if (action === "confirm") {
          instance.confirmButtonLoading = true;
          try {
            // if (val == "saveAllEdit") {
            saveAllEdit();
            // } else {
            //   saveAll();
            // }
            done();
          } catch (error) {
            instance.confirmButtonLoading = false;
          }
        } else {
          done();
        }
      },
    });
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`保存失败: ${error.message || "未知错误"}`);
      console.error("保存失败:", error);
    }
  }
};
// 自动保存航线
const autoSave = async () => {
  // 首次加载不自动保存
  if (isInitialLoad.value) {
    return;
  }

  // 根据项目规范，只有当有起飞点和航点数据时才自动保存
  // 修复：只有起飞点没有航点数据时不调用自动保存
  // 修复：删除完航点只剩下起飞点时不调用自动保存
  if (!hasTakeoffPoint.value || !hasWaypointData.value || airlineList.value.length === 0) {
    return;
  }

  // 保存中 ElLoading
  // const loadingInstance = ElLoading.service({
  //   lock: true,
  //   text: "保存中...",
  //   background: "rgba(255, 255, 255, 0.7)",
  // });
  isSuccess.value = false;

  if (!is_has_takeOffRefPoint.value) {
    //没有设置起飞点
    ElMessage.error("请设置起飞点");
    return;
  } else {
    // 将布尔值转换为API需要的格式：true -> 0(选中)，false -> 1(未选中)
    // const wideType = form.wideType ? 0 : 1; // 0代表选中，1代表未选中
    // const zoomType = form.zoomType ? 0 : 1; // 0代表选中，1代表未选中
    const irType = form.irType; // 0代表选中，1代表未选中
    const visableType = form.visableType; // 0代表选中，1代表未选中
    if (visableType == 1 && irType == 1) {
      ElMessage({
        message: "请至少选择一种照片存储类型",
        type: "warning",
      });
      return;
    }

    const takeOffRefPoint = startdata.value.point.toString()
    // 深拷贝，避免响应式对象导致的循环引用
    const wayPoints = JSON.parse(JSON.stringify(airlineList.value));
    //处理高德的数组
    if (gaodeList.value && gaodeList.value.length > 0) {
      const gaodeData = JSON.parse(JSON.stringify(gaodeList.value));
      wayPoints.forEach((item, index) => {
        item.longitude = gaodeData[index].longitude;
        item.latitude = gaodeData[index].latitude;
      });
    }
    const time = formattedTotalTime.value;
    const params = {
      id: route.query.id,
      airlineName: ruleForm.airlineNameData, //form.airlineName,
      brandId: form.brandId, // 使用form中的brandId
      seriesId: form.seriesId, // 使用form中的seriesId
      modelId: form.modelId, // 使用form中的modelId
      // wideType: wideType,
      // zoomType: zoomType,
      wideType: 1,
      zoomType: 1,
      irType: irType,
      visableType: visableType,
      airlineHeightType: form.airlineHeightType,
      globalHeight: form.globalHeight,
      autoFlightSpeed: form.autoFlightSpeed,
      globalTransitionalSpeed: form.globalTransitionalSpeed,
      attitudeHead: form.attitudeHead,
      wayPointType: form.wayPointType,
      outOfControlAction: form.outOfControlAction,
      finishAction: form.finishAction,
      takeOffSecurityHeight: form.takeOffSecurityHeight,
      globalRTHHeight: form.globalRTHHeight,
      pointNum: airlineList.value.length,
      executeTime: time,
      totalDistance: form.totalDistance,
      wayPoints,
      takeOffRefPoint: takeOffRefPoint,
    };

    try {
      await ruleFormRef.value?.validate();
      const response = await editAirline(params);

      // 检查响应状态
      if (response.code === 200) {
        // ElMessage.success("保存成功");
        isSuccess.value = true;
        // 关闭所有弹窗
        closeAllPopups();
      } else {
        // 接口返回业务错误
        const errorMsg = response.message || response.msg || "保存失败";
        ElMessage.error(errorMsg);
      }
    } catch (err) {
      // 处理HTTP错误（如500、404等）
      if (err.response) {
        const { status, data } = err.response;
        let errorMsg = "操作失败";

        if (status === 500) {
          errorMsg = data?.message || data?.msg || "服务器内部错误";
        } else if (status === 404) {
          errorMsg = "接口不存在";
        } else if (status === 403) {
          errorMsg = "权限不足";
        } else if (status === 401) {
          errorMsg = "未授权访问";
        } else {
          errorMsg = data?.message || data?.msg || `请求失败 (${status})`;
        }

        ElMessage.error(errorMsg);
      } else if (err.request) {
        // 网络错误
        ElMessage.error("网络连接失败，请检查网络设置");
      } else {
        // 其他错误
        ElMessage.error(err.message || "操作失败");
      }
    } finally {
      // loadingInstance.close();
    }
  }
};

// 防抖版本的自动保存函数
const debouncedAutoSave = () => {
  // 清除之前的定时器
  if (autoSaveDebounceTimer) {
    clearTimeout(autoSaveDebounceTimer);
  }

  // 设置新的防抖定时器
  autoSaveDebounceTimer = setTimeout(() => {
    autoSave();
  }, AUTO_SAVE_DEBOUNCE_DELAY);
};
const saveAllEdit = async (isback = true) => {
  if (!is_has_takeOffRefPoint.value) {
    //没有设置起飞点
    ElMessage.error("请设置起飞点");
    return;
  }
  // 将布尔值转换为API需要的格式：true -> 0(选中)，false -> 1(未选中)
  // const wideType = form.wideType ? 0 : 1; // 0代表选中，1代表未选中
  // const zoomType = form.zoomType ? 0 : 1; // 0代表选中，1代表未选中
  const irType = form.irType; // 0代表选中，1代表未选中
  const visableType = form.visableType; // 0代表选中，1代表未选中
  if (visableType == 1 && irType == 1) {
    ElMessage({
      message: "请至少选择一种照片存储类型",
      type: "warning",
    });
    return;
  }

  const takeOffRefPoint = startdata.value.point.toString()
  // 深拷贝，避免响应式对象导致的循环引用
  const wayPoints = JSON.parse(JSON.stringify(airlineList.value));
  //处理高德的数组
  if (gaodeList.value && gaodeList.value.length > 0) {
    const gaodeData = JSON.parse(JSON.stringify(gaodeList.value));
    wayPoints.forEach((item, index) => {
      item.longitude = gaodeData[index].longitude;
      item.latitude = gaodeData[index].latitude;
    });
  }
  // 保存中 ElLoading
  const loadingInstance = ElLoading.service({
    lock: true,
    text: "保存中...",
    background: "rgba(255, 255, 255, 0.7)",
  });
  isSuccess.value = false;
  const time = formattedTotalTime.value;
  const params = {
    id: route.query.id,
    airlineName: ruleForm.airlineNameData, //form.airlineName,
    brandId: form.brandId, // 使用form中的brandId
    seriesId: form.seriesId, // 使用form中的seriesId
    modelId: form.modelId, // 使用form中的modelId
    // wideType: wideType,
    // zoomType: zoomType,
    wideType: 1,
    zoomType: 1,
    irType: irType,
    visableType: visableType,
    airlineHeightType: form.airlineHeightType,
    globalHeight: form.globalHeight,
    autoFlightSpeed: form.autoFlightSpeed,
    globalTransitionalSpeed: form.globalTransitionalSpeed,
    attitudeHead: form.attitudeHead,
    wayPointType: form.wayPointType,
    outOfControlAction: form.outOfControlAction,
    finishAction: form.finishAction,
    takeOffSecurityHeight: form.takeOffSecurityHeight,
    globalRTHHeight: form.globalRTHHeight,
    pointNum: airlineList.value.length,
    executeTime: time,
    totalDistance: form.totalDistance,
    wayPoints,
    takeOffRefPoint: takeOffRefPoint,
  };
  try {
    await ruleFormRef.value?.validate();
    const response = await editAirline(params);

    // 检查响应状态
    if (response.code === 200) {
      ElMessage.success("保存成功");
      isSuccess.value = true;
      // 关闭所有弹窗
      closeAllPopups();
      // 返回列表
      if (isback) router.go(-1);
    } else {
      // 接口返回业务错误
      const errorMsg = response.message || response.msg || "保存失败";
      ElMessage.error(errorMsg);
    }
  } catch (err) {
    // 处理HTTP错误（如500、404等）
    if (err.response) {
      const { status, data } = err.response;
      let errorMsg = "操作失败";

      if (status === 500) {
        errorMsg = data?.message || data?.msg || "服务器内部错误";
      } else if (status === 404) {
        errorMsg = "接口不存在";
      } else if (status === 403) {
        errorMsg = "权限不足";
      } else if (status === 401) {
        errorMsg = "未授权访问";
      } else {
        errorMsg = data?.message || data?.msg || `请求失败 (${status})`;
      }

      ElMessage.error(errorMsg);
    } else if (err.request) {
      // 网络错误
      ElMessage.error("网络连接失败，请检查网络设置");
    } else {
      // 其他错误
      ElMessage.error(err.message || "操作失败");
    }
  } finally {
    loadingInstance.close();
  }

};
// 详情
const getDetail = async () => {
  const params = {
    id: route.query.id,
  };
  const { data } = await getAirlineById(params);

  // 添加空值检查
  if (!data) {
    ElMessage.error("获取航线详情失败：数据为空");
    return;
  }
  ruleForm.airlineNameData = data.airlineName
  // 将API返回的0/1格式转换为布尔值：0 -> true(选中)，1 -> false(未选中)
  // form.wideType = data.wideType === 0; // 0表示选中，转换为true
  // form.zoomType = data.zoomType === 0; // 0表示选中，转换为true
  form.airlineName = data.airlineName;
  form.irType = (data.irType == '' || data.irType == null) ? 0 : 1;
  form.visableType = (data.visableType == '' || data.visableType == null) ? 0 : 1;
  form.airlineHeightType = data.airlineHeightType || 0;
  form.autoFlightSpeed = data.autoFlightSpeed || 10;
  form.globalTransitionalSpeed = data.globalTransitionalSpeed || 10;
  form.attitudeHead = data.attitudeHead || 0;
  form.wayPointType = data.wayPointType || 1;
  form.outOfControlAction = data.outOfControlAction || 0;
  form.finishAction = data.finishAction || 0;
  form.takeOffSecurityHeight = data.takeOffSecurityHeight || 120; //安全起飞高度
  form.globalRTHHeight = data.globalRTHHeight || 120;
  form.totalDistance = data.totalDistance;
  form.executeTime = data.executeTime || '';
  form.takeOffRefPoint = data.takeOffRefPoint;
  // console.log(data.executeTime)
  // 设置品牌、系列、型号ID
  form.brandId = data.brandId;
  form.seriesId = data.seriesId;
  form.modelId = data.modelId;
  getBrand();

  drawDefaultRoute.value.points = convertToAllData(data.wayPoints);
  if (data.takeOffRefPoint) startdata.value.point = data.takeOffRefPoint.split(',')
  if (mapRef.value) {
    mapRef.value.getdrawDefaultRoute({
      takeOffRefPoint: data.takeOffRefPoint,
      wayPoints: data.wayPoints
    });
  }
  // airlineList.value = [];
  airlineList.value = data.wayPoints.map((wayPoint, i) => ({
    index: i,
    ...wayPoint
  }));
  defaultList.value = data.wayPoints || []; //保留默认数据
  gaodeList.value = data.wayPoints; //高德数组
  form.globalHeight = data.globalHeight
    ? Number(data.globalHeight)
    : airlineList.value[0]?.height
      ? Number(airlineList.value[0].height)
      : 100; //飞行高度
  // 检查动作是否需要警告
  checkAction();
  // 起点
  // if (data.wayPoints) {
  //   if (data.wayPoints.length > 0) {
  //     // 如果有默认航点数据，检查是否有起飞点数据
  //     // if (data.takeOffRefPoint && data.takeOffRefPoint.trim()) {
  //     //   // 有起飞点数据，设置为已设置状态
  //     //   // flayoneShow.value = false; // false表示起飞点已设置
  //     //   // flayShow.value = true;
  //     //   // hasTakeoffPoint.value = true; // 更新起飞点标志
  //     // } else {
  //     //   // 没有起飞点数据，设置为未设置状态
  //     //   // flayoneShow.value = true; // true表示起飞点未设置
  //     //   // flayShow.value = true;
  //     //   // hasTakeoffPoint.value = false; // 更新起飞点标志
  //     // }

  //     // 更新航点数据标志
  //     hasWaypointData.value = data.wayPoints.length > 0;
  //   } else {
  //     // 没有航点数据，设置为未设置状态
  //     // flayoneShow.value = true;
  //     // flayShow.value = true;
  //     // hasTakeoffPoint.value = false; // 更新起飞点标志
  //     // hasWaypointData.value = false; // 更新航点数据标志
  //   }
  // }

  // 初始化第一个航点的数据
  // if (airlineList.value.length > 0) {
  //   waypointIndex.value = 0;
  //   const firstWaypoint = airlineList.value[0];
  //   form_point.wayPointName = 0;
  //   form_point.longitude = firstWaypoint.longitude;
  //   form_point.latitude = firstWaypoint.latitude;
  //   form_point.positionType = firstWaypoint.positionType || 2;
  //   form_point.imageFormat = firstWaypoint.imageFormat || 0;
  //   form_point.attitudeHead = firstWaypoint.attitudeHead || 0;

  //   // 高度跟随判断
  //   if (firstWaypoint.height === form.globalHeight) {
  //     form_point.heightFollow = 1;
  //   } else {
  //     form_point.heightFollow =
  //       firstWaypoint.heightFollow !== undefined
  //         ? firstWaypoint.heightFollow
  //         : 0;
  //   }

  //   // 速度跟随判断
  //   if (firstWaypoint.waypointSpeed === form.autoFlightSpeed) {
  //     form_point.waypointSpeedFollow = 1;
  //   } else {
  //     form_point.waypointSpeedFollow =
  //       firstWaypoint.waypointSpeedFollow !== undefined
  //         ? firstWaypoint.waypointSpeedFollow
  //         : 0;
  //   }

  //   form_point.flightspeed =
  //     firstWaypoint.waypointSpeed !== undefined
  //       ? firstWaypoint.waypointSpeed
  //       : form.autoFlightSpeed;
  //   form_point.height =
  //     firstWaypoint.height !== undefined
  //       ? firstWaypoint.height
  //       : form.globalHeight;
  //   form_point.actions =
  //     firstWaypoint.actions && Array.isArray(firstWaypoint.actions)
  //       ? firstWaypoint.actions
  //       : [];
  //   form_point.algorithm = firstWaypoint.algorithmIds || [];
  //   form_point.shout = firstWaypoint.megaphoneOperate || {};
  //   form_point.algorithmExtends = firstWaypoint.algorithmExtendsByIds || [];

  //   // 处理动作数据，确保有正确的最大最小值
  //   if (
  //     form_point.actions &&
  //     Array.isArray(form_point.actions) &&
  //     form_point.actions.length > 0
  //   ) {
  //     form_point.actions = form_point.actions.map((action) => {
  //       switch (action.actionType) {
  //         case 1: // 悬停
  //           return { ...action, actionMin: 1, actionMax: 900 };
  //         case 2: // 无人机偏航角
  //           return { ...action, actionMin: -180, actionMax: 180 };
  //         case 3: // 云台俯仰角
  //           return { ...action, actionMin: -120, actionMax: 45 };
  //         case 7: // 相机变焦
  //           return { ...action, actionMin: 2, actionMax: 200 };
  //         case 9: // 开始等距间隔拍照
  //           return { ...action, actionMin: 1, actionMax: 900 };
  //         case 10: // 开始等时间隔拍照
  //           return { ...action, actionMin: 1, actionMax: 30 };
  //         default:
  //           return action;
  //       }
  //     });
  //   }
  // }
  // setTimeout(() => {
  //   formattedTotalTime.value = data.executeTime
  // }, 1000);
  // 初始化拖拽功能
  nextTick(() => {
    if (activeName.value == "2") {
      setTimeout(() => {
        initializeActionsSortable();
      }, 100);
    }
  });
  getflighttime(airlineList.value);

  // 数据加载完成后，设置初始加载标志为false
  isInitialLoad.value = false;
};
/**
 * 使用 Vincenty 公式计算两个经纬度之间的高精度距离（单位：米）
 * @param {Array<number>} coord1 - [纬度1, 经度1]
 * @param {Array<number>} coord2 - [纬度2, 经度2]
 * @returns {number} 两点之间的距离（米）
 * @throws {Error} 如果参数无效或计算不收敛
 */
const getPreciseDistance = (coord1, coord2) => {
  // 参数校验
  if (!Array.isArray(coord1) || !Array.isArray(coord2)) {
    throw new Error("参数必须是数组 [经度, 纬度]");
  }
  if (coord1.length !== 2 || coord2.length !== 2) {
    throw new Error("坐标格式错误，应为 [经度, 纬度]");
  }

  const [lon1, lat1] = coord1.map(Number); // 现在第一个是经度，第二个是纬度
  const [lon2, lat2] = coord2.map(Number);

  // 检查经纬度范围
  if (lat1 < -90 || lat1 > 90 || lat2 < -90 || lat2 > 90) {
    throw new Error("纬度必须在 -90 到 90 度之间");
  }
  if (lon1 < -180 || lon1 > 180 || lon2 < -180 || lon2 > 180) {
    throw new Error("经度必须在 -180 到 180 度之间");
  }

  // WGS84 椭球参数
  const a = 6378137.0; // 地球长半轴（米）
  const b = 6356752.314245; // 地球短半轴（米）
  const f = (a - b) / a; // 扁率

  const φ1 = lat1 * Math.PI / 180; // 纬度1（弧度）
  const φ2 = lat2 * Math.PI / 180; // 纬度2（弧度）
  const λ1 = lon1 * Math.PI / 180; // 经度1（弧度）
  const λ2 = lon2 * Math.PI / 180; // 经度2（弧度）

  const L = λ2 - λ1; // 经度差
  const U1 = Math.atan((1 - f) * Math.tan(φ1)); // 辅助计算
  const U2 = Math.atan((1 - f) * Math.tan(φ2)); // 辅助计算

  let λ = L;
  let λPrev; // 初始化 λPrev
  let sinσ, cosσ, σ, sinα, cosSqα, cos2σM;
  let iterations = 0;
  const maxIterations = 200;

  do {
    λPrev = λ; // 存储当前 λ 值用于下一次比较

    const sinU1 = Math.sin(U1);
    const cosU1 = Math.cos(U1);
    const sinU2 = Math.sin(U2);
    const cosU2 = Math.cos(U2);

    sinσ = Math.sqrt(
      (cosU2 * Math.sin(λ)) ** 2 +
      (cosU1 * sinU2 - sinU1 * cosU2 * Math.cos(λ)) ** 2
    );

    if (sinσ === 0) return 0; // 两点重合

    cosσ = sinU1 * sinU2 + cosU1 * cosU2 * Math.cos(λ);
    σ = Math.atan2(sinσ, cosσ);
    sinα = (cosU1 * cosU2 * Math.sin(λ)) / sinσ;
    cosSqα = 1 - sinα ** 2;
    cos2σM = cosσ - (2 * sinU1 * sinU2) / cosSqα;

    if (isNaN(cos2σM)) cos2σM = 0; // 赤道情况

    const C = (f / 16) * cosSqα * (4 + f * (4 - 3 * cosSqα));
    λ = L + (1 - C) * f * sinα *
      (σ + C * sinσ * (cos2σM + C * cosσ * (-1 + 2 * cos2σM ** 2)));

    iterations++;
    if (iterations > maxIterations) {
      throw new Error("Vincenty 公式计算不收敛");
    }
  } while (Math.abs(λ - λPrev) > 1e-12);

  const uSq = cosSqα * (a ** 2 - b ** 2) / (b ** 2);
  const A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
  const B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
  const Δσ = B * sinσ * (
    cos2σM + B / 4 * (
      cosσ * (-1 + 2 * cos2σM ** 2) -
      B / 6 * cos2σM * (-3 + 4 * sinσ ** 2) * (-3 + 4 * cos2σM ** 2)
    )
  );

  const s = b * A * (σ - Δσ); // 最终距离（米）
  return s;
}
// 飞行时长
const getflighttime = () => {
  let val = airlineList.value
  totalTime.value = 0;
  if (val.length > 1) {
    // console.log(val)
    // 1. 起飞时间计算
    let takeoffTime = 0;
    if (startdata.value.point && startdata.value.point.length > 2) {
      takeoffTime = startdata.value.point[2] / form.globalTransitionalSpeed
      // console.log(startdata.value.point[2], startdata.value.point[2] / form.globalTransitionalSpeed);

      // 2. 起飞点到第一个航点的时间
      let arr1 = [startdata.value.point[0], startdata.value.point[1]]
      let arr2 = [val[0].longitude, val[0].latitude];
      takeoffTime += (getPreciseDistance(arr1, arr2) / val[0].waypointSpeed);
      // console.log(getPreciseDistance(arr1, arr2), (getPreciseDistance(arr1, arr2) / val[0].waypointSpeed));
    }
    // 航线飞行时间，航点动作时间(悬停)
    let airlineTime = 0;
    let hoverTime = 0;
    for (let i = 0; i < val.length; i++) {
      if (i < val.length - 1) {
        let a1 = [val[i].longitude, val[i].latitude];
        let a2 = [val[i + 1].longitude, val[i + 1].latitude];
        airlineTime += (getPreciseDistance(a1, a2) / val[i].waypointSpeed);
        // console.log(getPreciseDistance(a1, a2), (getPreciseDistance(a1, a2) / val[i].waypointSpeed));
      } else {
        let timeh = Math.abs(val[i].height - form.globalRTHHeight);
        let lasthtime = timeh / form.globalTransitionalSpeed;//因为没有返航降落速度，直接用了起飞速度
        airlineTime += lasthtime
        // console.log(timeh, lasthtime);
        if (startdata.value.point && startdata.value.point.length > 2) {
          let arr1 = [startdata.value.point[0], startdata.value.point[1]]
          let arr2 = [val[i].longitude, val[i].latitude];
          airlineTime += getPreciseDistance(arr1, arr2) / val[i].waypointSpeed
          // console.log(getPreciseDistance(arr1, arr2), getPreciseDistance(arr1, arr2) / val[i].waypointSpeed);
          let fgtime = form.globalRTHHeight / form.globalTransitionalSpeed
          airlineTime += fgtime
          // console.log(form.globalRTHHeight, fgtime);
        }

        // let a1 = [val[i].longitude, val[i].latitude]
        // let a2 = [val[i + 1].longitude, val[i + 1].latitude]
        // airlineTime += (getPreciseDistance(a1, a2) / val[i].waypointSpeed)
      }
      if (Array.isArray(val[i].actions) && val[i].actions.length > 0) {
        for (let action of val[i].actions) {
          if (action.actionType === 1) {
            hoverTime += action.actionValue;
          }
        }
      }
      // if (val[i].actions && Array.isArray(val[i].actions)) {
      //   const hoverAction = val[i].actions.find(
      //     (action) => action.actionType === 1
      //   );
      //   if (hoverAction && hoverAction.actionValue) {
      //     hoverTime += hoverAction.actionValue;
      //   }
      // }
    }
    totalTime.value = Number(takeoffTime) + Number(airlineTime) + Number(hoverTime);
    // console.log(Number(takeoffTime), Number(airlineTime), Number(hoverTime))
    // console.log(Number(takeoffTime) + Number(airlineTime) + Number(hoverTime))
  }
  // getPreciseDistance();
  // startdata.value.point
  // if (distanceArray.value[0] && form.globalTransitionalSpeed) {
  //   takeoffTime = distanceArray.value[0] / form.globalTransitionalSpeed;
  // }
  // form.autoFlightSpeed
  // 2. 起飞点到第一个航点的时间
  // let takeoffToFirstWaypointTime = 0;
  // if (distanceArray.value[1] && form.globalTransitionalSpeed) {
  //   takeoffToFirstWaypointTime =
  //     distanceArray.value[1] / form.globalTransitionalSpeed;
  // }

  // 3. 航点间飞行时间计算
  // let waypointFlightTimes = [];
  // 去掉 distanceArray 前两个，去掉 val 最后一个
  // distanceArray 从索引2开始，对应 val 从索引0开始（但要去掉最后一个）
  // for (let i in val) {
  //   const distanceIndex = i + 2; // distanceArray 从第三个元素开始
  //   const waypointItem = val[i];

  //   if (distanceArray.value[distanceIndex] && waypointItem.waypointSpeed) {
  //     const waypointTime =
  //       distanceArray.value[distanceIndex] / waypointItem.waypointSpeed;
  //     waypointFlightTimes.push({
  //       waypointIndex: i,
  //       distance: distanceArray.value[distanceIndex],
  //       speed: waypointItem.waypointSpeed,
  //       time: waypointTime,
  //     });
  //   }
  // }

  // 4. 计算每个航点的悬停时间
  // let hoverTimes = [];
  // for (let i = 0; i < val.length; i++) {
  //   const waypointItem = val[i];
  //   let hoverTime = 0;

  //   // 检查该航点是否有悬停动作（actionType === 1）
  //   if (waypointItem.actions && Array.isArray(waypointItem.actions)) {
  //     const hoverAction = waypointItem.actions.find(
  //       (action) => action.actionType === 1
  //     );
  //     if (hoverAction && hoverAction.actionValue) {
  //       hoverTime = hoverAction.actionValue;
  //     }
  //   }
  //   hoverTimes.push({
  //     waypointIndex: i,
  //     hoverTime: hoverTime,
  //   });
  // }
  // // 5. 计算总飞行时间（包括悬停时间）
  // const totalHoverTime = hoverTimes.reduce(
  //   (sum, item) => sum + item.hoverTime,
  //   0
  // );
  // totalTime.value =
  //   takeoffTime +
  //   takeoffToFirstWaypointTime +
  //   waypointFlightTimes.reduce((sum, item) => sum + item.time, 0) +
  //   totalHoverTime;

  // return {
  //   takeoffTime,
  //   takeoffToFirstWaypointTime,
  //   waypointFlightTimes,
  //   hoverTimes,
  //   totalHoverTime,
  // };
};
// 获取距离数组
const getdistanceArray = (val) => {
  distanceArray.value = val;
  // 当距离数组更新时，重新计算飞行时长
  // if (airlineList.value && airlineList.value.length > 0) {
  //   getflighttime(airlineList.value);
  // }
};
// 转换函数：将所有航点合并成一个 point 数组
const convertToAllData = (waypoints) => {
  // 安全检查：确保 waypoints 是数组
  if (!waypoints || !Array.isArray(waypoints)) {
    console.warn("convertToAllData: waypoints 不是有效的数组:", waypoints);
    waypoints = [];
  }

  const points = waypoints.map((wp) => [wp.longitude, wp.latitude, wp.height]); // 所有点

  // 处理起飞点数据 - 优先使用保存的位置信息
  let startPoint = [];
  // if (form.takeoffLongitude && form.takeoffLatitude) {
  //   // 使用保存的起飞点位置
  //   startPoint = [
  //     form.takeoffLongitude,
  //     form.takeoffLatitude,
  //     form.takeOffSecurityHeight || 120,
  //   ];
  // } else if (takeOffRefPoint) {
  //   // 如果没有保存的位置，使用传入的起飞点
  //   const coords = takeOffRefPoint
  //     .split(",")
  //     .map((coord) => parseFloat(coord.trim()));
  //   if (coords.length >= 2) {
  //     // 安全地获取高度，避免 points[0][2] 为空的情况
  //     const defaultHeight = points.length > 0 ? points[0][2] : 300;
  //     startPoint = [
  //       coords[0],
  //       coords[1],
  //       form.takeOffSecurityHeight || defaultHeight,
  //     ];
  //   }
  // }

  return points;
};
// 获取航点名称
const airlineClick = (val) => {
  // const waypointData = airlineList.value.find((item) => item.index == val);
  // selectedWayPoint.value = waypointData;
  selectedWayPoint.value = airlineList.value[val]
  getClose();
};

// 航点双击事件
const waypointDoubleClick = (waypointData) => {
  activeName.value = "2";//切换为航点设置
  form_point.wayPointName = waypointData.index;
  getstopenroute(waypointData.index);
};
// 当开始绘制航线时，关闭重设起飞点
const getdrawingNext = (value) => {
  is_has_takeOffRefPoint.value = value;
  isResettingTakeoff.value = false;
};

// 添加此方法来处理编辑航线名称的逻辑
const editAirlineName = () => {
  // 编辑前先保存当前的航线名称，用于取消时恢复
  ruleForm.airlineNameData = form.airlineName;
  showEditAirlineName.value = true;
};

// 保存航线名称的方法
const saveAirlineName = async () => {
  // 检查航线名称是否有效
  if (!isAirlineNameValid.value) {
    ElMessage({
      type: "error",
      message: "航线名称不能为空",
    });
    return;
  }
  // showEditAirlineName.value = false;
  // 根据是否有id来决定调用哪个保存接口
  // if (route.query.id) {
  // 有id，调用编辑接口
  await saveAirlineNameEdit();
  // } else {
  //   // 没有id，调用添加接口
  //   await saveAirlineNameAdd();
  // }
};

// 取消航线名称编辑
const cancelAirlineNameEdit = () => {
  // 恢复原来的航线名称
  ruleForm.airlineNameData = form.airlineName;
  showEditAirlineName.value = false;
};

// 添加计算属性来检查航线名称是否有效（不为空且不全为空格）
const isAirlineNameValid = computed(() => {
  return ruleForm.airlineNameData && ruleForm.airlineNameData.trim() !== "";
});

// 处理回车键事件，防止换行
const handleEnter = (event) => {
  event.preventDefault();
};

// 监听选中状态变化，自动同步到 form_point.wayPointName
// watch(selectedWayPoint, (newWayPoint) => {
//   if (newWayPoint && newWayPoint.index !== undefined) {
//     activeName.value = "2";
//     form_point.wayPointName = newWayPoint.index;
//     getstopenroute(newWayPoint.index);
//     setTimeout(() => {
//       showDataloading.value = false;
//     }, 300);
//   }
// });

// 监听 form_point.wayPointName 变化，自动同步到选中状态
watch(
  () => form_point.wayPointName,
  (newIndex) => {
    if (newIndex !== undefined && selectedWayPoint.value?.index !== newIndex) {
      const waypointData = airlineList.value.find(
        (item) => item.index === newIndex
      );
      if (waypointData) {
        selectedWayPoint.value = waypointData;
      }
    }
  }
);

// 监听动作数组变化，重新初始化拖拽排序
watch(
  () => form_point.actions,
  () => {
    if (
      activeName.value === "2" &&
      form_point.actions &&
      form_point.actions.length > 0
    ) {
      nextTick(() => {
        setTimeout(() => {
          initializeActionsSortable();
        }, 100);
      });
    }
  },
  { deep: true }
);

// 获取机场列表
const getAirportList = async () => {
  try {
    const params = {
      airportName: "",
      currentPage: "",
      pageSize: "",
    };
    const { data } = await getAirportListNoPage(params);
    if (data && data.length > 0) {
      airportList.value = data;
      if (mapRef.value) {
        mapRef.value.set_airportList(data);
      }
    } else {
      airportList.value = [];
    }
  } catch (error) {
    console.error("获取机场列表失败:", error);
    airportList.value = []; // 设置默认空数组
    ElMessage.error("获取机场列表失败");
  }
};

// 获取品牌列表
const getBrand = async () => {
  try {
    const { data } = await getBrandList();
    brandOptions.value = data || [];

    // 从路由参数中获取初始值
    const routeBrandId =
      route.query.brandId || form.brandId;
    const routeSeriesId =
      route.query.seriesId || form.seriesId;
    const routeModelId =
      route.query.modelId || form.modelId;

    // 如果路由中有品牌ID，则设置并加载对应的系列和型号
    if (routeBrandId) {
      // 检查品牌ID是否存在于品牌列表中
      const validBrand = brandOptions.value.find(
        (brand) => brand.id === routeBrandId
      );
      if (validBrand) {
        form.brandId = routeBrandId;
        await getSeriesByBrandId();

        // 如果路由中有系列ID，则设置并加载对应的型号
        if (routeSeriesId) {
          form.seriesId = routeSeriesId;
          const selectedSeries = seriesList.value.find(
            (series) => series.id === routeSeriesId
          );
          if (selectedSeries) {
            currentModels.value = selectedSeries.models || [];

            // 如果路由中有型号ID，则设置
            if (routeModelId) {
              form.modelId = routeModelId;
            } else if (
              selectedSeries.models &&
              selectedSeries.models.length > 0
            ) {
              // 默认选中第一个型号
              form.modelId = selectedSeries.models[0].id;
            }
          }
        } else if (seriesList.value && seriesList.value.length > 0) {
          // 默认选中第一个系列
          const firstSeries = seriesList.value[0];
          form.seriesId = firstSeries.id;

          // 获取第一个系列的型号列表
          currentModels.value = firstSeries.models || [];

          // 默认选中第一个型号
          if (firstSeries.models && firstSeries.models.length > 0) {
            form.modelId = firstSeries.models[0].id;
          }
        }
      } else {
        // 设置为第一个品牌（如果有）
        if (brandOptions.value.length > 0) {
          form.brandId = brandOptions.value[0].id;
          await getSeriesByBrandId();
        }
      }
    } else if (brandOptions.value.length > 0) {
      // 默认选中第一个品牌
      form.brandId = brandOptions.value[0].id;
      // 获取第一个品牌的系列列表
      await getSeriesByBrandId();
    }
  } catch (error) {
    ElMessage.error("获取品牌列表失败");
    console.error(error);
  }
};

// 监听航线飞行速度变化，更新所有设置为"跟随航线"的航点速度
const watchAutoFlightSpeed = watch(
  () => form.autoFlightSpeed,
  (newSpeed, oldSpeed) => {
    // 确保新速度是有效数字
    const numericNewSpeed = Number(newSpeed);
    if (isNaN(numericNewSpeed)) return;

    // 只更新勾选了"跟随航线"的航点速度
    if (airlineList.value && airlineList.value.length > 0) {
      airlineList.value.forEach((item) => {
        // 只有当航点设置为跟随航线时才更新速度
        if (item.waypointSpeedFollow === 1) {
          item.waypointSpeed = numericNewSpeed;
        }
        // 检查未跟随航线的航点，如果速度变得与航线速度一致，则自动勾选跟随
        // else if (item.waypointSpeedFollow === 0) {
        //   const speedDiff = Math.abs(item.waypointSpeed - numericNewSpeed);
        //   if (speedDiff < 0.01) {
        //     item.waypointSpeedFollow = 1;
        //   }
        // }
      });
      // 强制触发响应式更新
      airlineList.value = [...airlineList.value];
    }
  }
);

// 防抖函数，用于处理频繁的更新请求
let debounceTimer = null;
const debounceUpdateFollowingWaypointsHeight = (newHeight) => {
  // 清除之前的定时器
  if (debounceTimer) {
    clearTimeout(debounceTimer);
  }

  // 设置新的定时器
  debounceTimer = setTimeout(() => {
    updateFollowingWaypointsHeight(newHeight);
    debounceTimer = null;
  }, 100); // 100ms的防抖延迟
};

// 添加一个函数来更新所有勾选"跟随航线"的航点高度
const updateFollowingWaypointsHeight = (newHeight) => {
  // 确保新高度是有效数字
  const numericNewHeight = Number(newHeight);
  if (isNaN(numericNewHeight)) return;

  // 只更新勾选了"跟随航线"的航点高度
  if (airlineList.value && airlineList.value.length > 0) {
    const updatedList = airlineList.value.map((item, index) => {
      // 创建新对象确保响应式更新，同时保留所有属性
      const newItem = {
        ...item,
        height: item.heightFollow === 1 ? numericNewHeight : item.height
      };

      // 检查未跟随航线的航点，如果高度变得与航线高度一致，则自动勾选跟随
      // if (item.heightFollow === 0) {
      //   const heightDiff = Math.abs(item.height - numericNewHeight);
      //   if (heightDiff < 0.01) {
      //     newItem.heightFollow = 1;
      //   }
      // }

      return newItem;
    });

    // 强制触发响应式更新
    airlineList.value = updatedList;
  }

  // 触发自动保存
  // autoSave();
};

// 修改 watchGlobalHeight 监听器，避免重复代码
const watchGlobalHeight = watch(
  () => form.globalHeight,
  (newHeight, oldHeight) => {
    // 确保新高度是有效数字
    const numericNewHeight = Number(newHeight);
    if (isNaN(numericNewHeight)) return;

    // 只更新勾选了"跟随航线"的航点高度
    if (airlineList.value && airlineList.value.length > 0) {
      const updatedList = airlineList.value.map((item, index) => {
        // 创建新对象确保响应式更新，同时保留所有属性
        const newItem = {
          ...item,
          height: item.heightFollow === 1 ? numericNewHeight : item.height
        };

        // 检查未跟随航线的航点，如果高度变得与航线高度一致，则自动勾选跟随
        // if (item.heightFollow === 0) {
        //   const heightDiff = Math.abs(item.height - numericNewHeight);
        //   if (heightDiff < 0.01) {
        //     newItem.heightFollow = 1;
        //   }
        // }

        return newItem;
      });
      // console.log(updatedList)
      // 强制触发响应式更新
      airlineList.value = updatedList;
      // 只有在非初始加载状态下才触发自动保存
      // if (!isInitialLoad.value) {
      //   autoSave();
      // }
      // console.log(airlineList.value, 'airlineList.value')
      if (mapRef.value) {
        mapRef.value.getLineHeght(updatedList);
      }
    }
  }
);
// 起飞点高度
watch(() => form.takeOffSecurityHeight,
  (newHeight, oldHeight) => {
    // 确保新高度是有效数字
    const numericNewHeight = Number(newHeight);
    if (isNaN(numericNewHeight)) return;
    if (mapRef.value) {
      mapRef.value.getTakeOffSecurityHeight(numericNewHeight);
    }
  }
);
// 动作报错相关
const is_warning = ref(false);//是否有错误
const warning_list = ref([]);// 错误列表
// {
//   points:'',
//   question:'',
//   solution:''
// }
// 检查整个航线的动作是否有问题
const checkAction = () => {
  let isVideoRecording = '' // 跟踪未关闭的录像动作 id
  let isPicture = '' // 跟踪未关闭的间隔拍照动作 id
  let videoStartPoints = [] // 记录开始录像的航点
  let videoStartPoints_t = [] // 记录开始录像的航点
  let pictureStartPoints = [] // 记录开始间隔拍照的航点
  let pictureStartPoints_t = [] // 记录开始间隔拍照的航点
  let videoError = false;
  let pictureError = false;
  let last_has_tack_photo = false; // 照片的数组需不需要删除最后一个问题，最后一个没有结束也不报错
  // 遍历所有航线的 actions
  for (let i in airlineList.value) {
    for (let ii in airlineList.value[i].actions) {
      const action = airlineList.value[i].actions[ii]
      // 录像检测
      if (action.actionType === 6) {
        isVideoRecording = parseInt(i) + 1
        // if (isVideoRecording) {
        //   // 已有一个未关闭的开始录像
        //   videoError = true
        // }
        // if (videoStartPoints.indexOf(parseInt(i) + 1) == -1) {
        //   videoStartPoints.push(parseInt(i) + 1) // 添加航点编号（从1开始）
        // }
        // if (isVideoRecording) {
        // 已有一个未关闭的间隔拍照
        // videoError = true;
        if (!videoStartPoints.some(item => item.id === parseInt(i) + 1)) {
          videoStartPoints.push({
            id: parseInt(i) + 1,
            name: videoStartPoints.length > 1 ? '/开始录像' : '开始录像'
          })
        } else {
          isVideoRecording = ''
        }
        if (!videoStartPoints.some(item => item.id === parseInt(i) + 1) || !videoStartPoints_t.some(item => item.actionType === action.actionType)) {
          videoStartPoints_t.push({
            id: parseInt(i) + 1,
            ii,
            actionType: action.actionType,
            name: videoStartPoints_t.length > 1 ? '/开始录像' : '开始录像'
          })
        }
        // }
      }
      if (action.actionType === 8) {
        if (isVideoRecording != '') {
          isVideoRecording = ''
          if (videoStartPoints[videoStartPoints.length - 1].id == videoStartPoints_t[videoStartPoints_t.length - 1].id) {
            videoStartPoints_t.pop();
          }
          videoStartPoints.pop();
        }
      }
      // 拍照检测
      // 等距间隔拍照 等时间隔拍照
      // 间隔拍照检测
      if (action.actionType === 9 || action.actionType === 10) {
        last_has_tack_photo = false;
        isPicture = parseInt(i) + 1
        // 先记录开始拍照
        let name = '';
        if (action.actionType === 9) {
          name = '开始等距间隔拍照'
        } else if (action.actionType === 10) {
          name = '开始等时间隔拍照'
        }
        // console.log(isPicture)
        // pictureError = true;
        // 检测哪个节点有问题
        // 管他有没有问题先记上
        if (!pictureStartPoints.some(item => item.id === (parseInt(i) + 1))) {
          pictureStartPoints.push({
            id: parseInt(i) + 1,
            // actionType: action.actionType,
            // name: pictureStartPoints.length > 1 ? '/' + name : name
          }) // 添加航点编号（从1开始）
        } else {
          last_has_tack_photo = true;
        }
        // 检测节点哪个动作有问题
        // 管他有没有问题先记上
        if (!pictureStartPoints.some(item => item.id === (parseInt(i) + 1)) || !pictureStartPoints_t.some(item => item.actionType === action.actionType)) {
          pictureStartPoints_t.push({
            id: parseInt(i) + 1,
            ii,
            actionType: action.actionType,
            name: pictureStartPoints_t.length > 1 ? '/' + name : name
          })
        }
      }
      if (action.actionType === 11) {
        // 有结束就删掉上一个照片提示
        if (!last_has_tack_photo && pictureStartPoints.length > 0) {
          last_has_tack_photo = true;//砍一刀
          if (pictureStartPoints[pictureStartPoints.length - 1].id == pictureStartPoints_t[pictureStartPoints_t.length - 1].id) {
            pictureStartPoints_t.pop();
          }
          pictureStartPoints.pop();
          isPicture = '';
        }
      }
      // 拍照和全景拍照
      if (action.actionType === 4 || action.actionType === 5) {
        if (isPicture) {
          last_has_tack_photo = true
          // 已有一个未关闭的间隔拍照
          // if (pictureStartPoints.indexOf(isPicture) == -1) {
          //   pictureStartPoints.push(isPicture) // 添加航点编号（从1开始）
          // }
          // let name = '';
          // if (action.actionType === 4) {
          //   name = '拍照'
          // } else if (action.actionType === 5) {
          //   name = '全景拍照'
          // }
          // if (!pictureStartPoints.some(item => item.id === parseInt(i) + 1)) {
          //   pictureStartPoints.push({
          //     id: parseInt(i) + 1,
          //     // actionType: action.actionType,
          //     // name: pictureStartPoints.length > 1 ? '/' + name : name
          //   }) // 添加航点编号（从1开始）
          // }
          // if (!pictureStartPoints_t.some(item => item.actionType === action.actionType)) {
          //   pictureStartPoints_t.push({
          //     id: parseInt(i) + 1,
          //     ii,
          //     actionType: action.actionType,
          //     name: pictureStartPoints.length > 1 ? '/' + name : name
          //   })
          // }
        }
      }
    }
  }
  if (isVideoRecording != '' && videoStartPoints.length > 0) {
    if (videoStartPoints[videoStartPoints.length - 1].id == videoStartPoints_t[videoStartPoints_t.length - 1].id) {
      videoStartPoints_t.pop();
    }
    videoStartPoints.pop();
  }
  videoError = videoStartPoints.length > 0
  if (!last_has_tack_photo && pictureStartPoints.length > 0) {
    // 如果最后被删除点里有动作就一起删了，不是最后一个点的不在这删
    if (pictureStartPoints[pictureStartPoints.length - 1].id == pictureStartPoints_t[pictureStartPoints_t.length - 1].id) {
      pictureStartPoints_t.pop();
    }
    pictureStartPoints.pop();
  }
  pictureError = pictureStartPoints.length > 0;
  // 更新错误状态
  is_warning.value = videoError || pictureError
  warning_list.value = [];
  if (videoError) {
    let videoStartPoints_name_text = ''
    for (let i in videoStartPoints_t) {
      videoStartPoints_name_text += ((i == 0 ? '' : ',') + `"${videoStartPoints_t[i].name}"`)
    }
    warning_list.value.push({
      points: videoStartPoints,
      question: `${videoStartPoints_name_text}航点动作缺少"停止录像"动作"`,
      solution: `请在${videoStartPoints_name_text}动作后插入"停止录像"动作`
    })
  }
  if (pictureError) {
    // ${pictureStartPoints.length > 1 ? '间' : ''}
    let pictureStartPoints_name_text = ''
    for (let i in pictureStartPoints_t) {
      pictureStartPoints_name_text += ((i == 0 ? '' : ',') + `"${pictureStartPoints_t[i].name}"`)
    }
    warning_list.value.push({
      points: pictureStartPoints,
      question: `${pictureStartPoints_name_text}航点动作缺少"结束间隔拍照"动作"`,
      solution: `请在${pictureStartPoints_name_text}航点动作后插入"结束间隔拍照"动作`
    })
  }
  // 赋值航段动作
  set_segmentActions();
}
// 给航段动作赋值
const set_segmentActions = () => {
  let video_segmentAction = false;
  let picture_segmentAction = false;//等时间间隔拍照 id9
  let picture_segmentAction2 = false;//等间距间隔拍照 id10
  for (let i in airlineList.value) {
    for (let ii in airlineList.value[i].actions) {
      const action = airlineList.value[i].actions[ii]
      // 录像检测
      if (action.actionType === 6) {
        video_segmentAction = airlineList.value[i].actions[ii]
      }
      if (action.actionType === 8) {
        video_segmentAction = false;
      }
      // 间隔拍照检测
      if (action.actionType === 9) {
        picture_segmentAction = airlineList.value[i].actions[ii];
      }
      if (action.actionType === 10) {
        picture_segmentAction2 = airlineList.value[i].actions[ii];
      }
      if (action.actionType === 11) {
        picture_segmentAction = false;
        picture_segmentAction2 = false;
      }
    }
    let arr = []
    if (video_segmentAction) arr.push(video_segmentAction)
    if (picture_segmentAction) arr.push(picture_segmentAction)
    if (picture_segmentAction2) arr.push(picture_segmentAction2)
    airlineList.value[i].segmentActions = arr;
  }
}
// 生命周期
onMounted(() => {
  getAirportList();
  // 初始化高度模式范围，onMounted时不自动保存
  getheightmode(form.airlineHeightType, true);
  // 如果是编辑模式，获取详情
  if (route.query.id) {
    getDetail();
  } else {
    getBrand();
    // 新建模式下，数据加载完成后设置初始加载标志为false
    isInitialLoad.value = false;
  }

  // ruleForm.airlineNameData = form.airlineName;
  // 初始化拖拽功能
  nextTick(() => {
    setTimeout(() => {
      initializeActionsSortable();
    }, 500);
  });
});

onBeforeUnmount(() => { });
</script>

<style scoped lang="scss">
:deep(.el-slider__button-wrapper) {
  width: auto;
}

.pageStyle {
  position: relative;
  height: calc(100vh - 88px);
  // position: relative;
  // background: #fff;
  color: #303133;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.warning_box {
  position: absolute;
  left: 18%;
  top: 12.5vh;
  z-index: 1;
  width: 300px;
  max-height: 60vh;

  .warning-item {
    background-color: #ffffff;
    padding: 3px;
    font-size: 14px;
    font-weight: 400;
    border-radius: 4px;
    color: #333333;
    margin-bottom: 5px;

    .s {
      font-weight: bold;
    }

    .warning-item-header {}

    .warning-item-content {}
  }
}

.map-left {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1000;
  width: 17%;
  height: calc(100vh - 88px);
  padding-top: 20px;
  background: rgb(255 255 255 / 70%);
}

.airline-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 2px;

  img {
    width: 46px;
    height: 34px;
    padding: 5px 11px;
    background-color: rgb(242 242 242 / 14.9%);
    border-radius: 3px;
  }
}

.airline-header-update {
  display: flex;
  align-items: center;

  :deep(.el-input) {
    width: 80%;
  }

  p {
    width: 80%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .el-button {
    width: 20%;
  }
}

/* 添加禁用按钮的样式 */
.disabled-button {
  color: #c0c4cc !important;
  cursor: not-allowed !important;
}

.airline-distance {
  display: flex;
  padding: 10px 0;
  margin-bottom: 8px;
  text-align: center;
  background: #fff;
  border: 1px solid #dcdfe6;

  .flex-1 {
    border-right: 1px solid #e4e7ed;
  }

  .flex-1:last-child {
    border-right: none;
  }
}

.map-right {
  position: absolute;
  top: 0;
  right: 0;
  width: 17%;
  height: calc(100vh - 88px);
  background: rgb(255 255 255 / 70%);
  // overflow: scroll;

  .airline-setup {
    display: flex;
    width: 100%;
    margin: 10px 0;
    border: 1px solid #dcdfe6;

    div {
      width: 50%;
      height: 34px;
      font-size: 14px;
      line-height: 34px;
      text-align: center;
      background: #fff;
      border: 1px solid #fff;
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
    }

    .tab-item {
      background: #fff;
      border-right: none;
      border-radius: 4px 0 0 4px;
    }

    .tab-itemBg {
      color: #1989fa;
    }
  }

  .airline-fly {
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    margin: 8px;
    background: #fff;
    border: 1px solid #dcdfe6;
    border-radius: 4px;

    img {
      width: 16px;
      height: 13px;
      margin-right: 4px;
    }

    .text {
      color: #1989fa;
    }
  }

  .airline-img {
    padding: 10px;
    margin: 8px;
    background: #fff;
    border: 1px solid #dcdfe6;
    border-radius: 4px;

    .el-checkbox {
      margin-top: 5px;
      font-size: 14px;
      font-weight: normal;
      color: #303133;
    }

    .btn {
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      margin-top: 10px;
      font-size: 12px;

      p {
        // flex: 1;
        height: 32px;
        line-height: 32px;
        text-align: center;
        background-color: rgb(242 242 242 / 14.9%);
        border: 1px solid #dcdfe6;
        border-radius: 4px;

        span {
          padding: 0 6px;
        }
      }

      p:first-child {
        margin: 0 8px 8px 0;
      }

      .activeBtn {
        color: #1989fa;
        border: 1px solid #1989fa;
        // background-color: rgb(0 204 255 / 20.8%);
      }
    }

    .select {
      width: 100%;
      margin-top: 10px;

      :deep(.el-select__wrapper) {
        color: #303133;
        background: transparent;
      }
    }

    .airBtn {
      width: 100%;
      margin-top: 10px;
      font-weight: normal;
      color: #303133;
      background: #f0f2f5;
      border: none;
      border-radius: 4px;
    }
  }

  .save {
    width: calc(100% - 16px);
    height: 40px;
    margin: 8px;
    background: #1989fa;
    border-radius: 4px;
  }

  .airline-setting {
    position: relative;
    justify-content: space-between;

    :deep(.address .el-input__wrapper) {
      height: 32px;
      line-height: 32px;
    }

    .du {
      position: absolute;
      top: 0;
      right: -8px;
    }
  }

  .airline-slider {
    display: flex;
    align-items: center;
    margin: 10px 0;

    .el-button {
      width: 16px;
      height: 16px;
      padding: 0 5px 2px;
      font-size: 16px;
      color: #fff;
      background: #c0c4cc;
      border: none;
      border-radius: 50%;
    }

    :deep(.el-slider__button) {
      width: 11px;
      height: 11px;
      border: none;
    }
  }
}

.search-input {
  box-shadow: 0 2px 6px rgb(0 0 0 / 30%);
}

.search-results {
  position: absolute;
  top: 80px;
  left: 20px;
  z-index: 999;
  width: 400px;
}

.result-item {
  padding: 10px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.result-item:hover {
  background-color: #f5f5f5;
}

.result-name {
  margin-bottom: 5px;
  font-weight: bold;
}

.result-address {
  font-size: 12px;
  color: #666;
}

.result-distance {
  margin-top: 5px;
  font-size: 12px;
  color: #409eff;
}

.airline-stoproute {
  cursor: pointer;
  padding: 12px;
  margin: 8px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;

  .blue {
    color: #409eff;
  }

  .bgimg {
    margin: 0 4px 0 4px;
    background-color: rgb(242 242 242 / 14.9%);
    border: 1px solid #dcdfe6;
    border-radius: 2px;

    img {
      width: 25px;
    }
  }

  // .bgimg:nth-child(5n) {
  //   margin: 0;
  // }

  .text {
    height: 34px;
    font-size: 14px;
    line-height: 34px;
  }
}

.airline-distanceblue {
  border: 1px solid #2f69eb;
}

.airline-wavy {
  padding: 10px;
  margin-bottom: 10px;
  font-size: 12px;
  background: #f0f2f5;
  // border: 1px solid #dcdfe6;
  border-radius: 5px;

  &:nth-child(2) {
    margin-top: 5px;
  }

  &:last-child {
    margin-bottom: 0; // 覆盖默认的 margin-bottom
  }

  img {
    width: 15px;
    height: 14px;
    margin-right: 5px;
  }
}

:deep(.el-select__selected-item.el-select__placeholder) {
  color: #303133;
}

:deep(.el-radio) {
  font-weight: normal;
  color: #303133;
}

:deep(.el-checkbox) {
  font-weight: normal;
  color: #303133;
}

.m-l-5 {
  margin-left: 5px;
}

:deep(.el-input__wrapper) {
  height: 20px;
  background: #e4e7ed;
  border-radius: 4px;
  box-shadow: none;
}

.bgimg {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.bgimg:hover::after {
  // position: absolute;
  // bottom: 100%;
  // left: 50%;
  // padding: 6px 10px;
  // margin-bottom: 5px;
  // font-size: 14px;
  // white-space: nowrap;
  // content: '拍摄模式';
  // background: #fff;
  // border: 1px solid #e4e7ed;
  // border-radius: 4px;
  // box-shadow: 0 2px 12px 0 rgb(0 0 0 / 6%);
  // transform: translateX(-50%);
}

.el-slider {
  margin: 0 10px;

  :deep(.el-slider__bar) {
    background: linear-gradient(79deg, #00ccd0 0%, #3a6af0 100%);
    box-shadow: 0 0 8px 0 rgb(97 137 202 / 43%);
  }
}

// :deep(.el-tooltip__popper) {
// font-size: 14px;
//  font-weight: 400;
// color: #303133;
// border: 1px solid #E4E7ED;
// }

:deep(.el-checkbox__label) {
  padding-left: 4px;
}

:deep(.custom-confirm-box) {
  .el-message-box__btns .el-button--small {
    padding: 8px 16px;
    font-size: 14px;
  }
}

.backbtn {
  position: absolute;
  bottom: 10px;
  width: calc(100% - 20px);
  font-size: 14px;
  font-weight: 500;
  line-height: 40px;
  color: #fff;
  text-align: center;
  cursor: pointer;
  background: #2f69eb;
  border-radius: 4px;
}

.sortable-item:hover {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.sortable-item:first-child {
  margin-top: 10px;
}

/* 系列和型号列表样式 */
.list {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin-bottom: 10px;
}

.list-item {
  padding: 8px 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
  min-height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background: #e3f1ff;
    border-color: #1989fa;
    color: #1989fa;
  }

  &.active {
    background: #e3f1ff;
    border-color: #1989fa;
    color: #1989fa;
  }

  &::marker {
    content: none;
  }
}

/* 无人机品牌、系列、型号选择器样式 */
.select-container {
  position: relative;
  margin-bottom: 12px;
}

.select-label {
  display: block;
  margin-bottom: 6px;
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

/* 标记样式 */
.mark-icon {
  position: absolute;
  left: -22px;
  top: 50%;
  transform: translateY(-50%);
  background-color: #1989fa;
  color: white;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  z-index: 1;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.marginLeft {
  @media (min-width: 1900px) {
    margin-left: 8px;
  }
}

@media (min-width: 1900px) {
  .marginLeft {
    margin-left: 8px;
  }
}

/* 响应式处理 */
@media (max-width: 500px) {
  .list {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 350px) {
  .list {
    grid-template-columns: 1fr;
  }
}

/* 1440px屏幕适配 */
@media screen and (max-width: 1440px) {
  .waypoint-label {
    font-size: 12px !important;
  }

  .follow-checkbox {
    font-size: 10px !important;
  }

  :deep(.airline-setting .el-checkbox__label) {
    font-size: 10px !important;
  }

  .m-l-55 {
    font-size: 10px !important;
    margin: 0 !important;
  }

  :deep(.el-input__inner) {
    font-size: 10px !important;
  }

  .dragImg {
    width: 12px !important;
    height: 12px !important;
  }

  .delete-icon {
    width: 12px !important;
    height: 12px !important;
  }

  .numberWidth {
    width: 60px !important;
  }

  .sortable-item {
    padding: 6px !important;
  }
}

/* 1920px屏幕适配 */
@media screen and (min-width: 1920px) {
  .follow-checkbox {
    font-size: 12px !important;
  }
}
</style>